java - 改造和 OkHttp gzip 解码

标签 java retrofit okhttp

我想将答案作为 gzip 编码的 JSON 来使用的 REST 服务。它提供了 Content-Encoding: gzip,但我的 OkHttp 没有将其编码为可读文本,因此 JSON 转换器会抛出异常。

---> HTTP GET https://rapla.dhbw-karlsruhe.de/rapla/events?resources=%5B%27rc85dbd6-7d98-4eb7-a7f6-b867213c73d8%27%5D&start=2015-09-01&end=2015-12-31
Accept-Encoding: gzip, deflate
Accept: application/json
Authorization: *not posted*
Content-Type: application/json;charset=utf-8
---> END HTTP (no body)
<--- HTTP 200 https://rapla.dhbw-karlsruhe.de/rapla/events?resources=%5B%27rc85dbd6-7d98-4eb7-a7f6-b867213c73d8%27%5D&start=2015-09-01&end=2015-12-31 (13ms)
Date: Tue, 24 Nov 2015 09:09:10 GMT
Server: Jetty(9.2.2.v20140723)
Expires: Tue, 01 Jan 1980 00:00:00 GMT
Pragma: no-cache
Cache-Control: no-cache, must-revalidate
Content-Encoding: gzip
Content-Type: application/json; charset=utf-8
Content-Disposition: attachment
Content-Length: 9684
Via: 1.1 rapla.dhbw-karlsruhe.de
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1448356149978
OkHttp-Received-Millis: 1448356149991

����WK�{��J�`k�_��Z����E�p�>3m�WMa�ג�ҵ�p�0��<��
... skipped rest of the body
E��>���S���n 
<--- END HTTP (9684-byte body)

根据Jake Whartons comment Content-Encoding: gzip Header 应该告诉 OkHttp 对 body 进行解码。

创建RestAdapter的代码是:

final RestAdapter adapter = new RestAdapter.Builder()
    .setEndpoint(baseUrl)
    .setClient(new OkClient(new OkHttpClient()))
    .setConverter(new GsonConverter(gson))
    .setLogLevel(RestAdapter.LogLevel.FULL)
    .build();
service = adapter.create(RaplaService.class);

gradle 依赖项是:

compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.6.0'

我的ServiceInterface中的方法:

@Headers({
        "Accept-Encoding: gzip, deflate",
        "Content-Type: application/json;charset=utf-8",
        "Accept: application/json"
})
@GET("/events")
List<Event> getEvents(@Header("Authorization") String token, @Query("resources") String resources, @Query("start") String start, @Query("end") String end);

最佳答案

替换这个:

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

有了这个:

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

当您提供自己的 Accept-Encoding header 时,您是在指示 OkHttp 您要自己进行解压缩。通过省略它,OkHttp 将负责添加 header 和解压缩。

关于java - 改造和 OkHttp gzip 解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33889840/

相关文章:

java - 在java中为neo4j节点生成j uuid的最佳方法是什么

java - GET 方法调用两次,代码为 301 和 200

android - 使用 Retrofit 解析以 JsonArray 作为根的 Json

android - 如何使用 Retrofit 发送 "fire and forget"异步调用?

android - OkHttp - 启用日志

android - 如何在从站点下载和解析 XML 文件时一起使用 Retrofit 和 SimpleXML?

java - 如何在一个类中处理多个线程?

java - Libgdx FileHandle读写多行

java - Kafka 生产者指标

android - 如何使用 Square 的 okHttp 设置不同数量的端口?