往后台传输json字符串为例,其他类型同样做法
自定义Request继承Volley自带的StringRequest
GzipRequest.java
public class GzipRequest extends StringRequest { private String mData = null; public GzipRequest(String url, Response.Listener<String> listener, @Nullable Response.ErrorListener errorListener) { super(url, listener, errorListener); } public GzipRequest(String url,String data, Response.Listener<String> listener, @Nullable Response.ErrorListener errorListener) { super(Method.POST,url, listener, errorListener); mData = data; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String,String> headers = new HashMap<String, String>(); headers.put("Charset", "UTF-8"); headers.put("Accept-Encoding", "gzip,deflate");//客户端允许接收GZIP headers.put("Content-Encoding", "gzip");//客户端发送GZIP内容 headers.put("Content-Type", "application/json");//根据后台要求,觉得Content-Type类型 return headers; } @Override public RetryPolicy getRetryPolicy() { return new DefaultRetryPolicy(); //setRetryPolicy(RetryPolicy policy);可自定义超时时间,重试次数等参数 } @Override public byte[] getBody() throws AuthFailureError { return mData == null ? super.getBody() : compress(mData); } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String result = uncompress(response.data); return Response.success(result, HttpHeaderParser.parseCacheHeaders(response)); //return super.parseNetworkResponse(response); } @Override protected void deliverResponse(String response) { } private byte[] compress(String str) { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (GZIPOutputStream gzip = new GZIPOutputStream(outStream)) { gzip.write(str.getBytes(StandardCharsets.UTF_8)); } return out.toByteArray(); }catch (Exception E){ return new byte[0]; } } private String uncompress(byte[] str){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str))) { int b; while ((b = gis.read()) != -1) { baos.write((byte) b); } }catch (Exception e){ return ""; } return new String(baos.toByteArray(), StandardCharsets.UTF_8); } }
以上,有帮助到你的话随手点个赞^^
作者:考特林
链接:https://www.jianshu.com/p/2bd2d3fca8bd
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦