【问题标题】:OkHttp enable/disable gzip compression on requestsOkHttp 在请求上启用/禁用 gzip 压缩
【发布时间】:2017-05-01 01:32:13
【问题描述】:

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

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

我已经添加了

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

或:

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

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

【问题讨论】:

    标签: java android retrofit retrofit2 okhttp


    【解决方案1】:

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

    Accept-Encoding: identity
    

    【讨论】:

    • ...并且请求正文没有压缩。为此,您需要:github.com/square/okhttp/blob/master/samples/guide/src/main/…
    • 谢谢,但我想 gzip 请求正文并查看启用或禁用 gzip 的大小差异。服务器没有使用 gzip 响应
    • 谢谢。为您的评论。我在OP上发布的链接也是如此。非常感谢
    【解决方案2】:

    我们可以使用这段代码

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 2018-08-20
      相关资源
      最近更新 更多