【发布时间】:2020-08-17 01:58:47
【问题描述】:
我有一个 Android 应用程序向 Flask 中的 REST API 发出 http 请求。我正在使用带有 okhttp3 的 Retrofit2 向带有 Raspbian Lite 的 Raspberry Pi 上托管的服务器发出请求。 我的问题是有时我得到一个 IOException -> java.net.ProtocolException: unexpected end of stream 但它有时会发生,有时它会完美运行。 http客户端搭建如下:
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent","myUserAgent")
.header("Connection","close")
.addHeader("Accept-Encoding", "identity")
.method(original.method(),original.body())
.build();
return chain.proceed(request);
}
});
Retrofit retrofit=null;
try {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
}catch (Exception e){
//Log.d
}
ApiService API_SERVICE=null;
try{
API_SERVICE = retrofit.create(ApiService.class);
}catch (Exception e){
//Log.d
}
return API_SERVICE;
我尝试过使用和不使用日志拦截器,使用 Accept-Encoding: identity 和 Conecction: close。但它不起作用。 答案的 Content-Lenght 是 4339(由邮递员表示),在拦截器中它也表示 4339 这是我得到的例外:
我在 Android API 28 中使用带有模拟器的 Android Studio。我的电脑和树莓派都通过以太网电缆连接到互联网。 我不明白为什么有时请求有效,而有时它直接进入 onFailure。 在服务器上,我总是得到一个 200 代码。请求被处理并正确返回响应。 我还能尝试什么?
【问题讨论】:
标签: android retrofit2 okhttp ioexception