我有一个Android应用程序,它可以向Flask中的一个REST API发出http请求,我使用Retrofit2和okhttp3向Raspberry Pi和Raspbian Lite的服务器发出请求。我使用Retrofit2和okhttp3向Raspberry Pi上的服务器发出请求,我的问题是,有时我得到一个IOException -> java.net.ProtocolException: unexpected end of streamBut it happens sometimes, other times it works perfectly.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. 但它不工作.The Content-Lenght of the answer is 4339 (it is indicated by postman) and in the intercetor it also indicates 4339This is the exception I get:
我正在使用Android Studio和Android API 28的模拟器。我的PC和树莓都是通过以太网电缆连接到互联网上的,我不明白的是,为什么有时候请求能成功,而其他时候它直接进入onFailure。在服务器上,我总是得到一个200代码。请求被处理并正确地返回响应.我还可以尝试什么?
似乎问题出在Android Studio模拟器上。我已经尝试将我的智能手机连接到Android studio,并在另一部智能手机上安装APK,但问题没有再现。
看起来像这个问题。https:/github.comsquareokhttpissues2738。. 所以,试试这个。
要么:
.addHeader("Connection", "close")
或者:.retryOnConnectionFailure(true)