Explain Codes LogoExplain Codes Logo

How to set HttpResponse timeout for Android in Java

java
http-client
async-task
retry-strategy
Alex KataevbyAlex Kataev·Sep 27, 2024
TLDR

Configure HTTP response timeout in Android using setConnectTimeout and setReadTimeout for HttpURLConnection:

HttpURLConnection conn = (HttpURLConnection) new URL("http://example.com").openConnection(); // These first 15 seconds are complimentary, goes great with coffee conn.setConnectTimeout(15000); // 15 sec conn.setReadTimeout(15000); // 15 sec

For OkHttp, apply timeouts in the OkHttpClient builder:

OkHttpClient client = new OkHttpClient.Builder() //Waiting game level: OKHttp .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(15, TimeUnit.SECONDS) .build();

Oldie but goldie, HttpParams can help with legacy HttpClient:

HttpParams httpParams = new BasicHttpParams(); //Retro vibes only HttpConnectionParams.setConnectionTimeout(httpParams, 15000); HttpConnectionParams.setSoTimeout(httpParams, 30000); // Don't let the socket hang HttpClient httpClient = new DefaultHttpClient(httpParams);

Intricacies of timeouts

Avoid staring at the screen waiting for DNS resolution, set a DNS resolution timeout. You can handle this without slowing down your UI with a custom DNSResolver class.

Handle retries like a boss

If at first you don't succeed, try again — but smarter! Use RETRY_HANDLER and httpClient.getParams() to finetune your retry mechanism upon encountering timeouts.

Mastering timeouts: basics to advanced

No, timeouts aren't just for toddlers. Understanding them can be instrumental in building responsive apps:

  • Don't play with fire, or main UI thread. Isolate network calls using AsyncTask or Executors.
  • DNS latency issues? Use Custom DNSResolver.
  • Consider SocketFactory with timeouts to prevent lower-level-network indefinite hangovers.
  • An exception to every rule: SocketTimeoutException and ConnectionTimeoutException. Handle these gracefully.

Timeout exceptions: the "Now, what?" guide

Timeout = SocketTimeoutException. How you handle this situation shapes your app:

  • Don't play dead. Catch and inform users appropriately.
  • Try, try, try again. Implement a retry strategy.
  • The proof is in the logs. Document everything for retrospective analysis and debugging.

Tools of the modern Android developer

Like food delivery and shopping, it's time to upgrade to more modern HTTP libraries such as OkHttp or Retrofit. They offer cleanliness, flexibility, and built-in mechanisms for handling almost everything, including timeouts.

References