OkHttp gzip post body

I am trying to migrate an Android project to OkHttp .

What am I interested in if OkHttp compresses the body of my POST requests using gzip?

I use it like this (from an example on the home page):

 RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); 

Will this RequestBody actually be gzip json if it is "big enough" or do I need to do it manually? As before, with AndroidHttpClient as follows:

 AndroidHttpClient.getCompressedEntity(json, context.getContentResolver()) 

If I need to do this manually, what's the best approach?

Thanks!

+6
source share
1 answer

According to the GitHub issues for OkHttp, we have to do this manually:

https://github.com/square/okhttp/issues/350

"At the moment, your best option is to do it manually: compress the content and add Content-Encoding: gzip."

Here's how I do it now:

 byte[] data = json.getBytes("UTF-8"); ByteArrayOutputStream arr = new ByteArrayOutputStream(); OutputStream zipper = new GZIPOutputStream(arr); zipper.write(data); zipper.close(); RequestBody body = RequestBody.create(JSON, arr.toByteArray()); Request request = new Request.Builder() .url(url) .post(body) .header("Content-Encoding", "gzip") .build(); 

I took the code from AndroidHttpClient and just used it inline without ByteArrayEntity: http://grepcode.com/file/repo1.maven.org/maven2/org.robolectric/android-all/4.2.2_r1.2-robolectric-0/android /net/http/AndroidHttpClient.java#AndroidHttpClient.getCompressedEntity%28byte%5B%5D%2Candroid.content.ContentResolver%29

+10
source

Source: https://habr.com/ru/post/976718/


All Articles