Coding⏱️ 2 min read📅 2026-05-31

How to Fix: How to set connection timeout with OkHttp

Set connection timeout and socket timeout using OkHttpClient.Builder().connectTimeout() and OkHttpClient.Builder().readTimeout() or writeTimeout() methods.

Quick Answer: Use OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS) and OkHttpClient.Builder().readTimeout(10, TimeUnit.SECONDS) or writeTimeout(10, TimeUnit.SECONDS) to set connection and read/write timeouts.

To set connection timeout and socket timeout using OkHttp, you can use the `setConnectTimeout()` and `setReadTimeout()` methods respectively.

⚠️ Common Causes

  • Not setting connection timeout can lead to a connection being left open indefinitely, consuming resources.

✅ Best Solutions to Fix It

Method 1: Setting Connection Timeout

  1. Step 1: Create an instance of OkHttpClient with a connection timeout.

Method 2: Setting Socket Timeout

  1. Step 1: Create an instance of OkHttpClient with both connection and socket timeouts.

🎯 Final Words

To set the timeout values, you can use the `setConnectTimeout()` method to specify the connection timeout in milliseconds and the `setReadTimeout()` method to specify the socket timeout in milliseconds. For example:

OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions