我开始将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 onErrorResponse(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
但同样的错误。
如果某人处于同一案件并有解决方案,请提前感谢您!
答案 0 :(得分:3)
这是如何覆盖标准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];
}
};
答案 1 :(得分:0)
public class CustomJsonObjectRequest extends JsonObjectRequest
{
public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest,Response.Listener listener, Response.ErrorListener errorListener)
{
super(method, url, jsonRequest, listener, errorListener);
}
@Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put(Constants.accesstoken, Globals.getInstance().getAccessToken());
Logger.debugE(Constants.accesstoken, headers.toString());
return headers;
}
}