我开始将Volley用于我的应用程序,并且我想为每个请求添加自定义标头作为安全标识符.
我正在使用JsonObjectRequest并覆盖getheaders().
JsonObjectRequest JsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JsONObject>() { @OverrIDe public voID onResponse(JsONObject response) { Log.d(TAG, response.toString()); } }, new Response.ErrorListener() { @OverrIDe public voID one rrorResponse(VolleyError error) { Log.d(TAG, error.toString()); } }) { @OverrIDe public Map<String, String> getheaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<>(); String mAPIKey = "123"; headers.put("APIKEY", mAPIKey); return headers; } @OverrIDe protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("param1", "1"); params.put("param2", "2"); params.put("param3", "3"); return params; } }; VolleySingleton.getInstance(getActivity()).addToRequestQueue(JsonObjectRequest);
但我得到这个错误:
E/Volley﹕ [23620] BasicNetwork.performRequest: Unexpected response code 401 for http://...
抛出AuthFailureError.
我也尝试使用StringRequest但是同样的错误.
如果有人在同一案件中并有解决方案,请提前感谢!
解决方法:
这是如何覆盖标准VolleyRequest中的标头的基本概念
VolleyRequest networkRequest = new VolleyRequest(request.gethttpMethod(), mUrlBase + request.getUrlSuffix(), responseListener, errorListener) { public String getbodyContentType() { return "application/Json; charset=" + getParamsEnCoding(); } @OverrIDe public Map<String, String> getheaders() throws AuthFailureError { HashMap<String, String> map = new HashMap<String, String>(); map.put("X-Device-Info","AndroID FOO bar"); map.put("Accept-Language", acceptLanguage); map.put("Content-Type", "application/Json; charset=UTF-8"); return map; } public byte[] getbody() throws AuthFailureError { try { String Json = request.toJson().toString(); if (Json.length() < 3) return ("{}").getBytes(); // log(Json); return Json.getBytes(getParamsEnCoding()); } catch (UnsupportedEnCodingException e) { Log.e(TAG, "getbody(): request has no Json"); e.printstacktrace(); } return new byte[0]; } };
总结 以上是内存溢出为你收集整理的android – 使用Volley库添加自定义标头全部内容,希望文章能够帮你解决android – 使用Volley库添加自定义标头所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)