Okhttp3请求网络开启Gzip压缩

来源:互联网 发布:网络侵权管辖 编辑:程序博客网 时间:2024/06/18 12:59

官方采用的是自定义拦截器的方式!
源码在:
okhttp/samples/guide/src/main/java/okhttp3/recipes/RequestBodyCompression.java
废话不多说,直接上代码:

import java.io.IOException;import okhttp3.Interceptor;import okhttp3.MediaType;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;import okio.BufferedSink;import okio.GzipSink;import okio.Okio;public class GzipRequestInterceptor implements Interceptor {    @Override    public Response intercept(Chain chain) throws IOException {        Request originalRequest = chain.request();        if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {            return chain.proceed(originalRequest);        }        Request compressedRequest = originalRequest.newBuilder()                .header("Content-Encoding", "gzip")                .method(originalRequest.method(), gzip(originalRequest.body()))                .build();        return chain.proceed(compressedRequest);    }    private RequestBody gzip(final RequestBody body) {        return new RequestBody() {            @Override            public MediaType contentType() {                return body.contentType();            }            @Override            public long contentLength() {                return -1; // 无法提前知道压缩后的数据大小            }            @Override            public void writeTo(BufferedSink sink) throws IOException {                BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));                body.writeTo(gzipSink);                gzipSink.close();            }        };    }}

然后构建OkhttpClient的时候,添加拦截器:

OkHttpClient okHttpClient = new OkHttpClient.Builder()     .addInterceptor(new GzipRequestInterceptor())//开启Gzip压缩    ...    .build();

后记

如果需要带有内容长度content-length的,可以查看这个issue:
Here’s the full gzip interceptor with content length, to whom it may concern:

原创粉丝点击