使用Transfer-Encoding改进客户端和响应:chunked

时间:2018-05-25 14:40:21

标签: java android http retrofit2 transfer-encoding

我正在开发一个从http://www.omdbapi.com/获取电影列表的Android示例应用。

REST服务是:

http://www.omdbapi.com/?s=star&apikey=d497e644

我使用Retrofit编写客户端。

public interface OmdbApi {
    @Streaming
    @GET("./")
    @Headers({"Cache-control: no-cache"})
    Call<Search> search(@Query("s") String search, @Query("apikey") String apiKey);

    @Streaming
    @GET("./")
    @Headers({"Cache-control: no-cache"})
    Call<FilmDetail> getFilm(@Query("i") String uid, @Query("apikey") String apiKey);
}

完整的源代码可用here

当我运行应用程序时,我获得以下响应(取自logcat):

OK http://www.omdbapi.com/?s=star&apikey=d497e644 (108ms)
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Cache-Control: public, max-age=86400
Expires: Sat, 26 May 2018 14:28:18 GMT
Last-Modified: Fri, 25 May 2018 05:39:04 GMT
Vary: *, Accept-Encoding
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
CF-Cache-Status: HIT
Server: cloudflare
CF-RAY: 4208b00c817b3db9-MXP
Connection: Keep-Alive

以下错误:

java.net.ProtocolException: unexpected end of stream
        at okhttp3.internal.http1.Http1Codec$ChunkedSource.read(Http1Codec.java:455)
        at okio.RealBufferedSource.read(RealBufferedSource.java:47)
okio.RealBufferedSource.exhausted(RealBufferedSource.java:57)
okio.InflaterSource.refill(InflaterSource.java:102)
okio.InflaterSource.read(InflaterSource.java:62)
okio.GzipSource.read(GzipSource.java:80)
okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:237)
okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
        at okhttp3.RealCall.execute(RealCall.java:77)
        at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:91)
com.abubusoft.filmfinder.service.repository.FilmRepository.lambda$findFilm$0$FilmRepository(FilmRepository.java:18)
com.abubusoft.filmfinder.service.repository.FilmRepository$$Lambda$0.run(Unknown Source:20)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)

经过一番调查后,我发现问题是答案有Transfer-Encoding: chunked。我该如何解决这个问题?

谢谢。

1 个答案:

答案 0 :(得分:1)

经过更多调查:

  • 我删除了@Streaming注释..它们并不有用。
  • 我所做的测试是在防火墙后面的PC上的模拟器上进行的。
  • 许多年前,
  • OkHttp遇到了一些问题,但是现在已经完全管理了分块转移。
  • 在同一台计算机上,在浏览器中调用相同的网址不会出现任何问题

我终于尝试了另一台机器,使用了JUnit测试和Android模拟器,我没有遇到任何问题。

最后,我确信代码可以正常工作,我用来开发应用程序的环境也存在转码编码的问题。

此处提供完整的源代码:

  1. android app
  2. junit test
  3. 我必须找到究竟是什么问题,我现在确定它不是Retrofit或我的客户定义或OkHttp。

    我希望我的经验可以帮助其他开发者。

    Byez

相关问题