首页 > 解决方案 > 添加参数时 volley 中出现意外的响应代码 401

问题描述

我有一个在邮递员上运行良好的 Api,但在我的代码中使用改造时运行良好。当我没有在正文中传递参数时,身份验证工作良好,但否则我得到错误 401

我之前使用改造,同样的错误然后我改为凌空但错误仍然存​​在。但是当我用邮递员测试时,它工作正常。注意:对于具有任何主体参数的调用,TOKEN 可以很好地与 API 配合使用

 StringRequest request = new StringRequest(
                Request.Method.POST, Config.API_URL_DETAILS
                , new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (!response.equals(null)) {
                    Log.i("tag", "lii"+response);
                } else {
                    Log.i("tag", "lii Data Null");
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("error is ", "" + error);
                error.printStackTrace();
            }
        }) {


            //This is for Headers If You Needed
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/x-www-form-urlencoded");
                params.put("Authorization", TOKEN);
                params.put("Accept", "application/json");
                return params;
            }

            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded; charset=UTF-8";
            }


            //Pass Your Parameters here
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();

                params.put("event_id", "30");
                params.put("longitude", String.valueOf(3.4));
                params.put("latitude", String.valueOf(6.6063));
                return params;
            }


        };


        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        queue.add(request);

我希望输出是 api 响应,但输出是响应代码 401.com.android.volley.AuthFailureError。

标签: androidapiauthorizationretrofitandroid-volley

解决方案


这是当请求从 API 端点被阻止时引起的。原因可能是格式错误的请求,

  • 检查您的请求类型 [GET/POST/ANY OTHER]
  • 检查请求的Header和Body

推荐阅读