I have an Android application that makes http requests to a REST API in Flask. I am using Retrofit2 with okhttp3 to make requests to a server hosted on a Raspberry Pi with Raspbian Lite. My problem is that sometimes I get an IOException -> java.net.ProtocolException: unexpected end of stream But it happens sometimes, other times it works perfectly. The http client is builded as follows:
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;
I have tried with and without logging interceptors, with Accept-Encoding: identity and Conecction: close. But it doesn't work. The Content-Lenght of the answer is 4339 (it is indicated by postman) and in the intercetor it also indicates 4339 This is the exception I get:
I am using Android Studio with an emulator in Android API 28. Both my pc and raspberry are connected by ethernet cable to the Internet. What I don't understand is why sometimes the request works and other times it goes straight to onFailure. On the server, I always get a 200 code. The request is processed and returns a response correctly. what else can i try?
It seems that the problem is with the Android Studio emulator. I have tried connecting my smartphone to android studio and installing the APK on another smartphone and the problem does not reproduce.