./> The first request to any backend takes as long as the connectTimeout is defined (5 seconds). Any subsequent calls go then really fast. Why is the first call waiting until the timeout exceeds before it succeeds?
slunyou10 opened this issue · comments
> The first request to any backend takes as long as the connectTimeout is defined (5 seconds). Any subsequent calls go then really fast. Why is the first call waiting until the timeout exceeds before it succeeds?
I may have found a bug. This is independent from API. Because when I change .connectTimeout(5, TimeUnit.SECONDS) to 10 seconds. Then the first call takes 10 seconds. And if I lower it to 1 second, then it takes 1 second to finish the first call.
I even tried to disable proxy .proxy(Proxy.NO_PROXY) but it didn't help.
import okhttp3.OkHttpClient import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.util.concurrent.TimeUnit object ApiService { private val SERVICE : ApiInterface init { val okHttpClient = OkHttpClient().newBuilder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(1, TimeUnit.SECONDS) .writeTimeout(1, TimeUnit.SECONDS) .build() val retrofit = Retrofit.Builder() .baseUrl(Config.BASE_URL) .client(okHttpClient) .addConverterFactory(MoshiConverterFactory.create()) .build() SERVICE = retrofit.create(ApiInterface::class.java) } fun getServerStatus() : Call<Map<String, ServerJson>> = SERVICE.getServers() }
I think this goes back to proxy and dns resolving issue over https.
So I used this to override the system dns.
implementation('com.squareup.okhttp3:okhttp-dnsoverhttps:4.9.0')
AND also disabled proxy.
init { val appCache = Cache(File("cacheDir", "okhttpcache"), 10 * 1024 * 1024) val bootstrapClient = OkHttpClient.Builder() .cache(appCache) .proxy(Proxy.NO_PROXY) .build() val dns = DnsOverHttps.Builder() .client(bootstrapClient) .url("https://dns.google/dns-query".toHttpUrl()) .bootstrapDnsHosts(InetAddress.getByName("8.8.4.4"), InetAddress.getByName("8.8.8.8")) .build() val okHttpClient = OkHttpClient().newBuilder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .dns(dns) .proxy(Proxy.NO_PROXY) .build() val retrofit = Retrofit.Builder() .baseUrl(Config.BASE_URL) .client(okHttpClient) .addConverterFactory(MoshiConverterFactory.create()) .build() SERVICE = retrofit.create(ApiInterface::class.java) }
This actually works as expected (no waiting time when doing the first call) when I build the app and run it on the phone. However when the app goes to background and comes back, it loses it. The next call takes again as long as the connectTimeout.
I'm using the latest version:
implementation('com.squareup.okhttp3:okhttp')
Now working perfect!!!
Originally posted by @willqz in square/okhttp#6486 (comment)