在我的Android应用程序中,我必须调用一个看起来像这样的Web服务
http://mywesite.com/demo/mob/getmenubycategory/1
我正在使用截击发送请求但结果是VolleyError 401
.我已经覆盖了getParams()
添加标题的方法,但它无法正常工作.
这是我的代码.
RequestQueue requestQueue = volleySingleton.getRequestQueue(); requestQueue.add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener() { @Override public void onResponse(JSONObject response) { Log.e(TAG, "onResponse = \n " + response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "response error \n" + error.networkResponse.statusCode); } }) { @Override protected Map getParams() throws AuthFailureError { try { Map map = new HashMap (); String key = "Authorization"; String encodedString = Base64.encodeToString(String.format("%s:%s", "USERNAME", "Password").getBytes(), Base64.NO_WRAP); String value = String.format("Basic %s", encodedString); map.put(key, value); return map; } catch (Exception e) { Log.e(TAG, "Authentication Filure" ); } return super.getParams(); } });
当我使用浏览器时,它会显示一个对话框,输入我的用户名和密码.如何使用Volley发送用户名和密码.
对于身份验证,恕我直言,你应该覆盖getHeaders
而不是getParams
,请尝试以下:
@Override public MapgetHeaders() throws AuthFailureError { Map headers = new HashMap<>(); String credentials = "username:password"; String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); headers.put("Content-Type", "application/json"); headers.put("Authorization", auth); return headers; }
希望能帮助到你!