Article From:https://www.cnblogs.com/ganchuanpu/p/9062788.html

First of all, OkHttp3 supports Gzip decompression, but we need to understand that it supports us to automatically join header when we request the request.Accept-Encoding: gzip,And when our server returns, there is a headerContent-Encoding: gzip
For more in-depth content, you can refer to the following article, which is very good!
Talk about HTTP gzip compression and common Android network framework

Then, when we submit a lot of data to the server, we hope to compress the data of post gzip.
Give the plan below!

programme

The official use iscustom interceptorThe way!
Source code:
okhttp/samples/guide/src/main/java/okhttp3/recipes/RequestBodyCompression.java
Not much talk, directly on the code:

 1 import java.io.IOException;
 2 
 3 import okhttp3.Interceptor;
 4 import okhttp3.MediaType;
 5 import okhttp3.Request;
 6 import okhttp3.RequestBody;
 7 import okhttp3.Response;
 8 import okio.BufferedSink;
 9 import okio.GzipSink;
10 import okio.Okio;
11 
12 public class GzipRequestInterceptor implements Interceptor {
13     @Override
14     public Response intercept(Chain chain) throws IOException {
15         Request originalRequest = chain.request();
16         if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
17             return chain.proceed(originalRequest);
18         }
19 
20         Request compressedRequest = originalRequest.newBuilder()
21                 .header("Content-Encoding", "gzip")
22                 .method(originalRequest.method(), gzip(originalRequest.body()))
23                 .build();
24         return chain.proceed(compressedRequest);
25     }
26 
27     private RequestBody gzip(final RequestBody body) {
28         return new RequestBody() {
29             @Override
30             public MediaType contentType() {
31                 return body.contentType();
32             }
33 
34             @Override
35             public long contentLength() {
36                 return -1; // It is impossible to know the size of the data after the compression
37             }
38 
39             @Override
40             public void writeTo(BufferedSink sink) throws IOException {
41                 BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
42                 body.writeTo(gzipSink);
43                 gzipSink.close();
44             }
45         };
46     }
47 }

When building OkhttpClient, add an Interceptor:

OkHttpClient okHttpClient = new OkHttpClient.Builder() 
    .addInterceptor(new GzipRequestInterceptor())//Open Gzip compression
    ...
    .build();

If you need a content length Content-Length, you can check this issue:
Here’s the full gzip interceptor with content length, to whom it may concern:

Reference: https://blog.csdn.net/tq08g2z/article/details/77311579

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *