我開始使用Volley作爲我的應用程序,我想爲每個請求添加自定義標頭作爲安全標識符。 我正在使用JsonObjectRequest
並覆蓋了getHeaders()
。爲Volley庫添加自定義標頭
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
但同樣的錯誤。
如果有人在同一個案中並有解決方案,請提前致謝!
你測試了一個命令行卷曲或者工作郵遞員鉻插件您的要求標準VolleyRequest覆蓋頭?你確實得到了迴應,這是預期的迴應嗎?你在期待什麼API?您是否嘗試攔截您的網絡流量(mitm代理)或記錄流量,以便您可以查看是否在請求上設置了標頭? – 2015-02-24 13:34:18
@ A.S。是的,我嘗試了郵差,它的工作原理。更多的時候我嘗試使用DefaultHttpClient和HttpGet它也可以。我會嘗試攔截我的網絡流量,但我懷疑標題未設置。 – Alex 2015-02-24 13:34:58
@ A.S。我不能安裝mitm代理,但我很確定標題沒有設置爲getHeaders() – Alex 2015-02-24 14:12:05