这里以post请求说明,get请求相似设置请求头及超时。
1.自定义request,继承com.android.volley.Request
2.构造方法实现(basecallback,为自定义的监听,实现Response.Listener,ErrorListener接口)--post请求
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方法
@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方法
@Override public RetryPolicy getRetryPolicy() { RetryPolicy retryPolicy = new DefaultRetryPolicy(SOCKET_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); return retryPolicy; }
5.请求参数组装:重写getBody方法
@Override public byte [] getBody() throws AuthFailureError { return params == null ? super .getBody() : params.getBytes(); }
结合上一篇gzip响应解析数据即可实现现在常见的http实现json数据的gzip传输
转载:http://blog.csdn.net/hpb21/article/details/12163371