使用Retrofit + OkHttp处理gzip响应的EOFException

时间:2015-02-20 01:45:35

标签: android rest retrofit okhttp

我尝试处理来自我的网络服务的gzipped响应,但我总是得到 EOFException:来源过早耗尽

这些是我的库的版本:

retrofit: 1.9.0
okhttp: 2.2.0
okhttp-urlconnection: 2.2.0
gson: 2.3.1

在我的代码和输出下面:

RestAdapter restAdapter = new RestAdapter.Builder()
    .setLogLevel(RestAdapter.LogLevel.FULL)
    .setClient(new OkClient(new OkHttpClient()))
    .setEndpoint("http://myserver.com/services")
    .build();

... 

@GET("/mobile/user/new") 
String registerNewAccount();

Charles(调试代理)注册的请求

GET /services/mobile/user/new HTTP/1.1
User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.3; GT-I9300 Build/JSS15J)
Host: myserver.com
Connection: Keep-Alive
Accept-Encoding: gzip

Charles

注册的回应
HTTP/1.1 200 OK
Date    Fri, 20 Feb 2015 00:47:13 GMT
Server  Apache-Coyote/1.1
Content-Encoding    gzip
Content-Type    application/json
Content-Length  32
Via 1.1 myserver.com
Keep-Alive  timeout=5, max=100
Connection  Keep-Alive

改造日志输出

<--- HTTP 200 http://myserver.com/services/mobile/user/new (666ms)
Date: Fri, 20 Feb 2015 00:59:44 GMT
Server: Apache-Coyote/1.1
Content-Type: application/json
Via: 1.1 myserver.com
Keep-Alive: timeout=5, max=100
Proxy-Connection: Keep-alive
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1424393970658
OkHttp-Received-Millis: 1424393971268

---- ERROR http://myserver.com/services/mobile/user/new
java.io.EOFException: source exhausted prematurely
    at okio.InflaterSource.read(InflaterSource.java:77)
    at okio.GzipSource.read(GzipSource.java:80)
    at okio.RealBufferedSource$1.read(RealBufferedSource.java:298)
    at java.io.InputStream.read(InputStream.java:163)
    at retrofit.Utils.streamToBytes(Utils.java:43)
    at retrofit.Utils.readBodyToBytesIfNecessary(Utils.java:81)
    at retrofit.RestAdapter.logAndReplaceResponse(RestAdapter.java:483)
    at retrofit.RestAdapter.access$500(RestAdapter.java:107)
    at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:338)
    at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
    at $Proxy0.registerNewAccount(Native Method)
    at com.myapp.tasks.RegisterUserTask.doInBackground(RegisterUserTask.java:36)
    at com.myapp.tasks.RegisterUserTask.doInBackground(RegisterUserTask.java:19)
    at android.os.AsyncTask$2.call(AsyncTask.java:287)
    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
    at java.lang.Thread.run(Thread.java:841)
D/Retrofit(9508): ---- END ERROR

任何帮助都将非常感激:)

1 个答案:

答案 0 :(得分:0)

使用curl尝试相同请求时会发生什么?确保使用--compressed启用响应压缩。如果我猜,我怀疑你正在谈论的服务器正在发送Content-Length未压缩的长度;他们应该将其设置为压缩长度。