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:
阅读全文
1 0
- Okhttp3请求网络开启Gzip压缩
- 如何开启gzip压缩
- .htaccess开启Gzip压缩
- apache开启gzip压缩
- nginx 开启 gzip 压缩
- HttpWebRequest开启gzip压缩
- wamp 开启gzip压缩
- 开启gzip压缩传输
- thinkphp开启GZIP压缩
- django开启gzip压缩
- Tomcat开启Gzip压缩
- Tomcat 开启Gzip压缩
- apache开启gzip压缩
- apache 开启gzip压缩
- Apache 开启Gzip 压缩
- Nginx开启Gzip压缩
- resin开启gzip压缩
- Nginx开启gzip压缩
- jsp页面时间转时间戳
- 车牌识别系统
- ibatis里面if else 用法
- cordova工程webview注入本地js库的方法
- 操作系统之典型调度算法
- Okhttp3请求网络开启Gzip压缩
- 堆排序实现
- 树结构练习——判断给定森林中有多少棵树
- 正则表达式
- git 撤销commit
- AUTODESK.FABRICATION.CAMDUCT.V2017.WIN64-ISO\
- W tensorflow/core/platform/cpu_feature_guard.cc:45
- java后台开发-hibernateTools自动构建实体类及常见错误
- wireshark插件开发