Volley 请求/接收内容 GZIP压缩

往后台传输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
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞