OkHttp enable/disable gzip compression on requests

懵懂的女人 提交于 2021-02-18 20:59:42

问题


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.


回答1:


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

Accept-Encoding: identity



回答2:


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();    
}


来源:https://stackoverflow.com/questions/41164299/okhttp-enable-disable-gzip-compression-on-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!