I need to make 50 http GET requests as fast as possible with Retrofit in Android. I am using Retrofit with OkHttp. Currently Retrofit is doing a poor job vs plain Java ThreadPoolExecutor
and HttpUrlConnection
: about 50sec for Retrofit and 30sec for plain HttpUrlConnection
for all 50 requests, if I set the pool size 20 for ThreadPoolExecutor
and for Retrofit / OkHttp I set okHttpClient.dispatcher().setMaxRequests(20);
.
If I look at logcat I can see that Retrofit is doing maximum of 5 concurrent requests no matter what I set in setMaxRequests()
while with ThreadPoolExecutor
there are as many concurrent requests as there are available worker threads.
Is there anything I can do to make Retrofit faster? I don't want to switch to HttpUrlConnection
because Retrofit is so elegant and easy to use.
I tried providing custom ThreadPoolExecutor
to OkHttp but no time improvement from this:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
ExecutorService exec = new ThreadPoolExecutor(20, 20, 1, TimeUnit.HOURS, new LinkedBlockingQueue<>());
Dispatcher d = new Dispatcher(exec);
builder.dispatcher(d);
OkHttpClient okHttpClient = builder.build();
okHttpClient.dispatcher().setMaxRequests(20);
I make all requests to the same endpoint, if this matters
Custom construction of network process Underlying Retrofit, it is using Reflection. If we want to extend some class from it, might not be possible due to it is final by default. So if you want to have more control over your own network process, using OkHttp directly should provide you that flexibility.
Access token headers logic with OkHttp Interceptors Retrofit is a powerful library for handling HTTP requests in Android apps. “A type-safe HTTP client for Android and Java.” According to the Retrofit official documentation. The retrofit wouldn't be that powerful without the OkHttp library.
OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.
Solution 1: Sharing Default OkHttp Instance In order to make them share a single OkHttp instance, you can simply pass it explicitly on the builder: OkHttpClient okHttpClient = new OkHttpClient(); Retrofit retrofitApiV1 = new Retrofit. Builder() . baseUrl("https://futurestud.io/v1/") .
Since they are all going to the same host, have you tried:
okHttpClient.dispatcher().setMaxRequestsPerHost(20);
Dispatcher.setMaxRequestsPerHost
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With