改进:如何在不使用Content-Encoding的情况下解析GZIP的响应:gzip标头 [英] Retrofit: how to parse GZIP'd response without Content-Encoding: gzip header

查看:536
本文介绍了改进:如何在不使用Content-Encoding的情况下解析GZIP的响应:gzip标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理GZIP发送的服务器响应.响应带有标题

I'm trying to process a server response which is GZIP'd. The response comes with a header

Content-Type: application/x-gzip

但没有标题

Content-Encoding: gzip

如果我使用代理添加该标头,则可以很好地解析响应. 我对服务器没有任何控制权,因此无法添加标头.

If I add that header using a proxy, the response gets parsed just fine. I don't have any control over the server, so I can't add the header.

我可以强制将Retrofit视为GZIP内容吗?有没有更好的办法? 服务器的URL为: http://crowdtorch.cms.s3.amazonaws.com/4474 /Updates/update-1.xml

Can I force Retrofit to treat it as GZIP content? Is there a better way? The URL for the server is: http://crowdtorch.cms.s3.amazonaws.com/4474/Updates/update-1.xml

推荐答案

有比重新发明轮子更好的方法.只需自己添加Content-Encoding标头即可.

There is a better way than reinventing the wheel. Just add the Content-Encoding header yourself.

.addNetworkInterceptor((Interceptor.Chain chain) -> {
    Request req = chain.request();
    Headers.Builder headersBuilder = req.headers().newBuilder();

    String credential = Credentials.basic(...);
    headersBuilder.set("Authorization", credential);

    Response res = chain.proceed(req.newBuilder().headers(headersBuilder.build()).build());

    return res.newBuilder()
        .header("Content-Encoding", "gzip")
        .header("Content-Type", ""application/json")
        .build();
})

实际上,您的代码是使用内部代码(例如JDK的com.sun软件包)的弊端的经典示例. RealResponseBody不再具有该构造函数.

In fact, your code is a classic example of the evils of using internal code (like com.sun packages from the JDK). RealResponseBody doesn't have that constructor anymore.

这篇关于改进:如何在不使用Content-Encoding的情况下解析GZIP的响应:gzip标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆