Reputation: 185
When I download json files by using retrofit, it takes way too much time every time.
I am using retrofit with okhttp to get json data and display in recyclerview. I am using interceptor to include keep-alive header as well. However requests take quite a lot time in comparison to google's firestore database. I think keep alive is not working properly and every request is opening new connections and that's why it's taking too long to load.
Api Code:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
ConnectionPool connectionPool = new ConnectionPool(10, 10, TimeUnit.MINUTES);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.connectionPool(connectionPool)
.connectTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES);
httpClient.interceptors().add(logging);
httpClient.interceptors().add(new Interceptor() {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws
IOException {
Request original = chain.request();
// Customize the request
Request request = original.newBuilder()
.header("Connection", "Keep-Alive")
.method(original.method(), original.body())
.build();
Response response = chain.proceed(request);
if (!response.isSuccessful() || response.code()==503) {
connectionPool.evictAll();
return chain.proceed(request);
} else {
// Customize or return the response
return response;
}
}
});
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
postService = retrofit.create(PostService.class);
public interface PostService {
@POST
Call<PostList> getPostList(@Url String url);
}
When I am using this code, it's taking over 8 seconds to load a 40kb file over a 10mbps wifi connection and even 4G connection. Whereas it hardly takes 1 second to load same data from firebase firestore.
In fact I queried 400kb data from firestore and it took only 4 seconds to load and 400 kb file from retrofit takes so long that application literally freezes.
I use Glide to load images and Glide takes less than 2 seconds to load 100kb images.
So I guess I am doing something seriously wrong here because Glide is quite fast, firestore is quite fast only retrofit with okhttp is very slow.
Can anyone tell me what have done wrong here?
Thank you.
Upvotes: 0
Views: 2594
Reputation: 185
Okay I solved it, When I downloaded a normal file by retrofit and read it by InputStream, then it was taking way too long. But when same data is accessed in json format, it took no more than 1 second. I think retrofit should be only used to get json data and not normal files.
Upvotes: 1