I am trying to migrate my Android project to OkHttp.
What I am wondering is if OkHttp will compress the body of my POST
requests with gzip?
I am using it like this (from the 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 gzip the json if it's "big enough", or do I need to do this manually? Like I did before with AndroidHttpClient
like this:
AndroidHttpClient.getCompressedEntity(json, context.getContentResolver())
If I need to do it manually, what is the best approach?
Thank you!
According to GitHub issues for OkHttp, we should do it manually:
https://github.com/square/okhttp/issues/350
"For the time being your best option is to do it manually: compress the content and add Content-Encoding: gzip."
This is how I'm doing 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 the AndroidHttpClient from here, and just using it inline without the 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
Knowing it's too late to answer but if anyone might need it in future.
A newer and easier way to do this is by following
val request = Request.Builder().url("…")\ .addHeader("Content-Encoding", "gzip")\ .post(uncompressedBody.gzip())\ .build()
More details can be found here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With