Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP FAILED: java.io.IOException: unexpected end of stream exception while making https request

We are previously using http apis and now we have migrated to https, with same code we are facing the exception HTTP FAILED: java.io.IOException: unexpected end of stream (this is for some device and for some network calls). We are using the OkHttp and Retrofit from android app. Below is our code

@Provides
    @ApplicationScope
    OkHttpClient provideOkHttpClientV2(
            HttpLoggingInterceptor logging,
            Interceptor headerInterceptor) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();

    //Removed custom timeout units
    return builder.addInterceptor(headerInterceptor)
            .addInterceptor(logging)
            .retryOnConnectionFailure(true)
            .readTimeout(100, TimeUnit.SECONDS)
            .connectTimeout(100, TimeUnit.SECONDS)
            .build();

 }

@Provides
@ApplicationScope
Interceptor provideRetrofitHeaderV2(final SharedPreferencesUtil sharedPreferencesUtil) {
    return new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            Request.Builder builder = original.newBuilder();
            builder.header("Content-Type", "application/json")
                    .method(original.method(), original.body());
            if (sharedPreferencesUtil != null) {
                if (sharedPreferencesUtil.isLogin()) {

                    String loginToken = sharedPreferencesUtil.getLoginToken();
                    builder.addHeader("Authorization", "Bearer " + loginToken);
                }
            }

            builder.addHeader("Connection", "close");

            Request request = builder.build();
            return chain.proceed(request);
        }
    };
}

@Provides
@ApplicationScope
HttpLoggingInterceptor provideLoggingInterceptorV2() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    if (BuildConfig.DEBUG) {
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    } else {
        logging.setLevel(HttpLoggingInterceptor.Level.NONE);
    }
    return logging;
}

@Provides
@ApplicationScope
Retrofit provideRetrofitV2(OkHttpClient okHttpClient) {
    return new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .baseUrl(BuildConfig.BASE_URL)
            .client(okHttpClient)
            .build();
}```

Things we have already tried:

  • Add header with addHeader("Connection", "close")
  • Add connection pool to limit the ideal connections
  • increase the timeout time

Any help will be appreciated, we are facing this issue for quite some time now.

like image 622
Asheesh Avatar asked Jun 09 '26 04:06

Asheesh


1 Answers

I just had this happen and figured out a workaround. This was caused by the use of the HttpLoggingInterceptor. Through debugging into the okhttp code I found that it was throwing that error because the length of the body did not match what the content length header in the response was. If it receives a content header it uses a FixedLengthSource and that will throw the "unexpected end of stream" error when it is read. You can see this in the source https://github.com/square/okhttp/blob/okhttp_3.9.x/okhttp/src/main/java/okhttp3/internal/http1/Http1Codec.java openResponseBody method

As a workaround I added a response interpreter to my builder that strips out the content-length header which causes it to use an UnknownLengthSource.

 private static final Interceptor REWRITE_CONTENT_LENGTH_INTERCEPTOR = new Interceptor() {
    @Override public Response intercept(Interceptor.Chain chain) throws IOException {
      Response originalResponse = chain.proceed(chain.request());
      return originalResponse.newBuilder().removeHeader("Content-Length")
              .build();
    }
  }; 
like image 158
Cynical Geek Avatar answered Jun 10 '26 19:06

Cynical Geek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!