Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OkHttp enable/disable gzip compression on requests

I'm using Retrofit to manage my requests and want to make some tests to check de request size using or not using gzip.

By default does OkHttp performs gzip compression to requests or it must be implemented with an interceptor?

I've added

@Headers({
        "Accept-Encoding: gzip, deflate",
        "Content-Encoding: gzip"
})

or:

@Headers({
        "Content-Type: application/json;charset=utf-8",
        "Accept: application/json"
})

to my requests and did not see any change on the request length.

like image 618
Favolas Avatar asked Dec 15 '16 12:12

Favolas


2 Answers

OkHttp will do transparent gzip on response bodies unless you disable the feature with this header:

Accept-Encoding: identity
like image 133
Jesse Wilson Avatar answered Nov 12 '22 07:11

Jesse Wilson


We can use this code

OkHttpClient client = new OkHttpClient();

Request request =  new Request.Builder().url(url)
                                                .addHeader("X-TOKEN", "Bearer " + Auth.getInstance(mContext).getToken())
                                                .addHeader("Accept-Encoding", "gzip")
                                                .build();

Response response = client.newCall(request).execute();

if (responseCode == 200) {
    // Regular JSON parsing to model
    ItemModel itemModel = LoganSquare.parse(response.body().byteStream(), ItemModel.class);
    long responseSize = response.body().contentLength();  

    // Manually decompress GZIP?
    ItemModel itemModel = LoganSquare.parse(new GZIPInputStream(response.body().byteStream()), ItemModel.class);
    long responseSize = response.body().contentLength();    
}
like image 2
Ahmad Aghazadeh Avatar answered Nov 12 '22 08:11

Ahmad Aghazadeh