通过Volley请求发送身份验证信息 [英] Send authentication information with Volley request
问题描述
在我的Android应用中,我必须调用一个看起来像这样的Web服务
In my Android app I have to call a web service which looks like this
http://mywesite.com/demo/mob/getmenubycategory/1
我正在使用截击发送请求,但结果为VolleyError 401
.
我已经覆盖了getParams()
方法来添加标题,但是它不起作用.
I am using the volley to send the request but the result is VolleyError 401
.
I have overridden the getParams()
method to add the header, but it is not working.
这是我的代码.
RequestQueue requestQueue = volleySingleton.getRequestQueue();
requestQueue.add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
@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<String, String> getParams() throws AuthFailureError {
try {
Map<String, String> map = new HashMap<String, String>();
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发送请求中的用户名和密码.
When I use my browser it shows a dialogue to enter my username and password. How can I send the username and password with the request using Volley.
推荐答案
对于IMHO身份验证,您应覆盖getHeaders
而不是getParams
,请尝试以下操作:
For authentication, IMHO, you should override getHeaders
instead of getParams
, please try the following:
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> 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;
}
希望有帮助!
这篇关于通过Volley请求发送身份验证信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!