利用volley進行http設置請求頭、超時及請求參數設置(post)

jopen 9年前發布 | 53K 次閱讀 Volley Android開發 移動開發

這里以post請求說明,get請求相似設置請求頭及超時。

1.自定義request,繼承com.android.volley.Request

2.構造方法實現(basecallback,為自定義的監聽,實現Response.Listener,ErrorListener接口)--post請求

  1. public BaseRequest(String url,String params, BaseCallback<T> callback)  
       {  
    super(Method.POST, url, callback);  
    this.callback = callback;  
    this.params = params;  
    Log.e(TAG, "request:" + params);  
    setShouldCache(false);  
       }

3.請求頭設置:重寫getHeaders方法

  1. @Override  
       public Map<String, String> getHeaders() throws AuthFailureError  
       {  
    Map<String, String> headers = new HashMap<String, String>();  
    headers.put("Charset", "UTF-8");  
    headers.put("Content-Type", "application/x-javascript");  
    headers.put("Accept-Encoding", "gzip,deflate");  
    return headers;  
       }

設置字符集為UTF-8,并采用gzip壓縮傳輸

4.超時設置:重寫getRetryPolicy方法

  1. @Override  
       public RetryPolicy getRetryPolicy()  
       {  
    RetryPolicy retryPolicy = new DefaultRetryPolicy(SOCKET_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);  
    return retryPolicy;  
       }

5.請求參數組裝:重寫getBody方法

  1. @Override  
       public byte[] getBody() throws AuthFailureError  
       {  
    return params == null ? super.getBody() : params.getBytes();  
       }

 

結合上一篇gzip響應解析數據即可實現現在常見的http實現json數據的gzip傳輸

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!