Bot*_*ito 3 android ioexception okhttp retrofit2
我有一个 Android 应用程序,它向 Flask 中的 REST API 发出 http 请求。我使用 Retrofit2 和 okhttp3 向带有 Raspbian Lite 的 Raspberry Pi 上托管的服务器发出请求。我的问题是,有时我会收到 IOException -> java.net.ProtocolException: 意外的流结束 但它有时会发生,其他时候它工作得很好。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;
Run Code Online (Sandbox Code Playgroud)
我尝试过使用和不使用日志拦截器,使用 Accept-Encoding: Identity 和 Conecction: close 。但这不起作用。答案的内容长度是 4339 (由邮递员指示),在拦截器中它也指示 4339 这是我得到的异常:
我正在使用 Android Studio 和 Android API 28 中的模拟器。我的电脑和树莓派都通过以太网电缆连接到互联网。我不明白的是为什么有时请求有效,有时则直接进入 onFailure。在服务器上,我总是收到 200 代码。请求被处理并正确返回响应。我还能尝试什么?
| 归档时间: |
|
| 查看次数: |
10853 次 |
| 最近记录: |