Frontier
First of all, OKHTTP3 is supported gzip decompression, but we have to understand that it is to support us when initiating the request to automatically join the header, and Accept-Encoding: gzip
our server returned when the header Content-Encoding: gzip
.
For more in-depth content, you can refer to read the following article, speaking very good!
Talk about HTTP gzip compression with common Android network framework
So, when we submit a lot of data to the server, we want to do the gzip compression of the post data, how to do?
Below is the solution!
Scheme
The official use of custom interceptors is the way!
Source code in:
Okhttp/samples/guide/src/main/java/okhttp3/recipes/requestbodycompression.java
Nonsense not much to say, 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;Ten import Okio. Okio; One A Public classGziprequestinterceptor implements Interceptor { - @Override - PublicResponse Intercept (Chain Chain) throws IOException { theRequest originalrequest =chain.request (); - if(Originalrequest.body () = =NULL|| Originalrequest.header ("content-encoding") !=NULL) { - returnchain.proceed (originalrequest); - } + -Request compressedrequest =Originalrequest.newbuilder () +. Header ("content-encoding","gzip") A . Method (Originalrequest.method (), Gzip (Originalrequest.body ())) at . Build (); - returnchain.proceed (compressedrequest); - } - - Privaterequestbody gzip (final requestbody body) { - return NewRequestbody () { in @Override - Publicmediatype ContentType () { to returnBody.contenttype (); + } - the @Override * Public Longcontentlength () { $ return-1;//The compressed data size cannot be known in advancePanax Notoginseng } - the @Override + Public voidWriteTo (Bufferedsink sink) throws IOException { ABufferedsink Gzipsink = Okio.buffer (NewGzipsink (sink)); the Body.writeto (gzipsink); + gzipsink.close (); - } $ }; $ } -}
Then, when building the okhttpclient, add the Interceptor:
New Okhttpclient.builder () . Addinterceptor (new gziprequestinterceptor ())// Turn on gzip compression ... . Build ();
Postscript
If you need a content-length content-length, you can view this issue:
Here's the full gzip interceptor with content length, to whom it may concern:
Ref: 77311579
OKHTTP3 requesting the network to turn on gzip compression