本文介绍了BasicNetwork.performRequest:意外的响应代码401 Android Volley库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

但是它得到了类似[10520] BasicNetwork.performRequest的错误:意外的响应代码401

But its getting Error like [10520] BasicNetwork.performRequest: Unexpected response code 401

我的代码是

RequestQueue queue = Volley.newRequestQueue(getActivity());
    JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, Server.URL, null,
            new Response.Listener<JSONObject>()
            {
                @Override
                public void onResponse(JSONObject response) {
                                // display response
                    hideProgressDialog();

                }
            },
            new Response.ErrorListener()
            {
                 @Override
                 public void onErrorResponse(VolleyError error) {
                     hideProgressDialog();
               }
            }
        );

        // add it to the RequestQueue
        queue.add(getRequest);

如何解决这个问题?

推荐答案

此错误表示您需要进行身份验证.您可以这样做,将getHeaders()添加到代码中,就像这样:

This error means you need to authenticate. You can do so adding getHeaders() to your code, so it goes like this:

RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, Server.URL, null,
        new Response.Listener<JSONObject>()
        {
            @Override
            public void onResponse(JSONObject response) {
                // display response
                hideProgressDialog();

            }
        },
        new Response.ErrorListener()
        {
             @Override
             public void onErrorResponse(VolleyError error) {
                 hideProgressDialog();
           }
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/json");
            String creds = String.format("%s:%s","username","password");
            String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
            params.put("Authorization", auth);
            return params;
        }
    );

queue.add(getRequest);

这篇关于BasicNetwork.performRequest:意外的响应代码401 Android Volley库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:11