Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OkHttp gzip post body

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!

like image 905
ullstrm Avatar asked Oct 14 '14 12:10

ullstrm


2 Answers

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

like image 112
ullstrm Avatar answered Nov 12 '22 19:11

ullstrm


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

like image 1
Syed Afeef Avatar answered Nov 12 '22 18:11

Syed Afeef