使用标题调用Volley请求时出现UnsupportedOperationException

时间:2016-04-20 16:47:28

标签: android android-volley

我尝试用Volley库发出呼叫请求。我想设置标题,但我得到java.lang.UnsupportedOperationException。你知道为什么,我该如何解决这个问题?

 public void getAccountInfo() {
            RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
            String url = "http://demo.gopos.pl/oauth/token";
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // Display the first 500 characters of the response string.
                            Log.e(TAG, "onResponse SUCCES!!" + response);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "That didn't work!");
            }

        }) {
            @Override
            public Map<String,String> getHeaders()throws AuthFailureError {
                Map<String,String> params = super.getHeaders();
                if(params==null)params = new HashMap<>();
                params.put("username","username");
                params.put("password","password");
                return params;
            }
        };
        queue.add(stringRequest);


    }

2 个答案:

答案 0 :(得分:20)

删除这两行:

 Map<String,String> params = super.getHeaders();
            if(params==null)params = new HashMap<>();

并加上这个:

   Map<String, String> params = new HashMap<>();

现在应该可以了。

答案 1 :(得分:0)

使用以下方法解决UnsupportedOperationException

override fun getHeaders(): MutableMap<String, String> {
    val header = HashMap<String, String>()
//  header[Constants.AUTH_TOKEN] = Constants.TOKEN_ID
    return header
}

这对我有用。