Retrofit onFailure throws "Unexpected end of stream" message in scrolling a endless scroll listener

1.2k Views Asked by At

I am loading server data in my app in endless scroll recyclerView using pagination with retrofit 2 library. But unfortunately after scrolling some page retrofit onFailure method throw a message showing "Unexpected end of stream". This message shows in arbitrary pages. sometimes it shows after scrolling 6 page and sometimes 12 page.And then retrofit doesn't loading anything.

can anyone give some suggestions that work?

3

There are 3 best solutions below

1
KIRAN CSN On

you can try

OkHttpClient client = new OkHttpClient.Builder()
    .retryOnConnectionFailure(true)
    .build();
5
Kushan On

I have faced this issue very recently and a combination of the following helped me

  1. For the OkHttpClient, set retry on connection failure to true

    OkHttpClient client = new OkHttpClient.Builder()
      .retryOnConnectionFailure(true)
      .build(); 
    
  2. Since this is caused by the connection not closing properly, add a Connection header to your retrofit request

    @Headers({
            "Connection: close"
    })
    @FormUrlEncoded
    @POST(Const.CHAT_LIST_API)
    Call<ResponseModel<ChatListModel>> chatList(
            @Field("user_id") int userid,
            @Field("device_type") int device_type,
            @Field("token") String token,
            @Field("language") String language,
            @Field("timezone") String timezone
    );
    

The above is the interface method that will be used to call the service. you need to add the headers part of the above to your services

Retry will basically reduce the chances and the actual solution is by the header

5
Manoj Perumarath On

Just add the header to your request

@Headers({"Connection: close"})

This means that you should close your connection after every request.