Volley 请求/接收内容 GZIP压缩

往后台传输json字符串为例,其他类型同样做法

自定义Request继承Volley自带的StringRequest

GzipRequest.java

public class GzipRequest extends StringRequest {

    private String mData = null;

    public GzipRequest(String url, Response.Listener listener, @Nullable Response.ErrorListener errorListener) {
        super(url, listener, errorListener);
    }

    public GzipRequest(String url,String data, Response.Listener listener, @Nullable Response.ErrorListener errorListener) {
        super(Method.POST,url, listener, errorListener);
        mData = data;
    }

    @Override
    public Map getHeaders() throws AuthFailureError {
        Map headers = new HashMap(); 
        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 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);
    }

}

以上,有帮助到你的话随手点个赞^^

你可能感兴趣的:(Volley 请求/接收内容 GZIP压缩)