2015-02-24 165 views
4

我開始使用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但同樣的錯誤。

如果有人在同一個案中並有解決方案,請提前致謝!

+0

你測試了一個命令行卷曲或者工作郵遞員鉻插件您的要求標準VolleyRequest覆蓋頭?你確實得到了迴應,這是預期的迴應嗎?你在期待什麼API?您是否嘗試攔截您的網絡流量(mitm代理)或記錄流量,以便您可以查看是否在請求上設置了標頭? – 2015-02-24 13:34:18

+0

@ A.S。是的,我嘗試了郵差,它的工作原理。更多的時候我嘗試使用DefaultHttpClient和HttpGet它也可以。我會嘗試攔截我的網絡流量,但我懷疑標題未設置。 – Alex 2015-02-24 13:34:58

+0

@ A.S。我不能安裝mitm代理,但我很確定標題沒有設置爲getHeaders() – Alex 2015-02-24 14:12:05

回答

3

這是一個基本的概念,如何在

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

是的,謝謝。這就是我正在做的,但似乎標題未設置... – Alex 2015-02-24 13:58:11

+1

亞歷克斯,我有同樣的問題,你有沒有得到一個解決方案? – JDOaktown 2016-07-11 18:14:26

+0

感謝你對我的回答工作 – 2017-05-26 10:37:07

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; 
    } 

} 
+0

雖然這段代碼片段可以解決這個問題,[包括解釋](http://meta.stackexchange.com/questions/ 114762/explain-completely-code-based-answers)真的有助於提高你的帖子的質量。請記住,你正在爲將來的讀者回答這個問題,而這些人可能不知道你的代碼建議的原因。儘量不要使用解釋性註釋來擠佔代碼,這會降低代碼和解釋的可讀性! – Rizier123 2016-03-07 10:35:22

+0

花點時間閱讀[編輯幫助](http://stackoverflow.com/editing幫助)在幫助中心。堆棧溢出的格式與其他站點不同。 – Rizier123 2016-03-07 10:35:30