Explain Codes LogoExplain Codes Logo

How to set connection timeout with OkHttp

java
connection-timeout
okhttp
retrofit
Nikita BarsukovbyNikita Barsukov·Aug 23, 2024
TLDR

Set timeouts swiftly in OkHttp using OkHttpClient.Builder() methods: connectTimeout(), readTimeout(), and writeTimeout(). Each demands a time value and TimeUnit. Here's a nifty example:

OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) // Give it 10 sec, or it's game over! .readTimeout(30, TimeUnit.SECONDS) // Wait 30 sec, even if it's like watching paint dry! .writeTimeout(15, TimeUnit.SECONDS) // Data has 15 sec to fly, or it's grounded! .build();

Above configurations afford 10 seconds for connection attempts, 30 seconds while awaiting data, and 15 seconds to bid adieu to our data. Modify as necessary.

Mastering the art of timeouts

Timeouts breed app responsiveness. A connection timeout is the time box for securing a successful connection, a read timeout is the patience limit to await data read completion, and a write timeout is your line in the sand for data sending.

Retrofit meets OkHttpClient

Unite Retrofit and a custom OkHttpClient with timeouts simply by passing the tailored client when constructing the Retrofit instance:

Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://example.com") .client(client) // Custom-configured OkHttpClient riding shotgun .build();

Customizing requests via interceptors

Sometimes, you need to fiddle with timeouts on the fly. Use addInterceptor() in OkHttpClient to add pre-request custom logic:

OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(chain -> { Request request = chain.request(); // Make the request do a barrel roll if needed... return chain.proceed(request); }) .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(15, TimeUnit.SECONDS) .build();

Fine-tuning timeout settings

Diverse network conditions often demand individualized timeout settings for each request—quite like custom room service! Clone the OkHttpClient and fiddle with the timeout values:

Request request = new Request.Builder() .url("http://example.com/resource") .build(); OkHttpClient clientWithCustomTimeout = client.newBuilder() .readTimeout(60, TimeUnit.SECONDS) // This request gets VIP treatment, 60 sec on the clock! .build(); Call call = clientWithCustomTimeout.newCall(request); Response response = call.execute();

Remember: creating a new OkHttpClient for every request has performance penalties. So clone and recycle, like an eco-friendly dev!

Grappling with timeouts

Timeouts can cause IOExceptions, just like chili peppers can cause heartburn. Always plan for proper exception handling:

try { Response response = call.execute(); // Dancing with the response data } catch (IOException e) { // Gracefully handle the salsa burn from the timeout }

Juggling legacy versions

For OkHttp's earlier versions, before OkHttpClient.Builder was the star, timeouts were set using setConnectTimeout and setReadTimeout:

OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(10, TimeUnit.SECONDS); client.setReadTimeout(30, TimeUnit.SECONDS);

While seemingly familiar, developers should transition to the builder pattern for code clarity and future compatibility.