java OkHttp 对请求启用/禁用 gzip 压缩

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41164299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:43:32  来源:igfitidea点击:

OkHttp enable/disable gzip compression on requests

javaandroidretrofitretrofit2okhttp

提问by Favolas

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

我正在Retrofit用来管理我的请求,并希望进行一些测试以检查使用或不使用 gzip 的请求大小。

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

默认情况下OkHttp对请求执行 gzip 压缩还是必须使用拦截器实现?

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.

到我的请求,并没有看到请求长度有任何变化。

回答by Jesse Wilson

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

OkHttp 将对响应主体执行透明 gzip,除非您使用此标头禁用该功能:

Accept-Encoding: identity

回答by Ahmad Aghazadeh

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