这里以post请求说明,get请求相似设置请求头及超时。
1.自定义request,继承com.android.volley.Request
2.构造方法实现(basecallback,为自定义的监听,实现Response.Listener,ErrorListener接口)--post请求
String params;
public static int SOCKET_TIMEOUT=20000;
public MyRequest(String url,String params, Response.Listener<String> listener, Response.ErrorListener errorListener){
super(Method.POST,url,listener,errorListener);
this.params=params;
}
-
</pre>
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(); }
-
6. 接收到gzip的数据 处理
-
@Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String parsed =getRealString(response.data); return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); }<pre name="code" class="java">private int getShort(byte[] data) { return (int) ((data[0] << 8) | data[1] & 0xFF); } public String getRealString(byte[] data) { byte[] h = new byte[2]; h[0] = (data)[0]; h[1] = (data)[1]; int head = getShort(h); boolean t = head == 0x1f8b; InputStream in; StringBuilder sb = new StringBuilder(); try { ByteArrayInputStream bis = new ByteArrayInputStream(data); if (t) { in = new GZIPInputStream(bis); } else { in = bis; } BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); } in.close(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }