Kotlin中如何使用OkHttp设置连接超时与套接字超时?
How to Set Connection and Socket Timeouts with OkHttp in Kotlin
Hey there! I totally get where you're coming from—OkHttp uses an immutable design, which means you can't tweak timeouts directly on an already-built OkHttpClient instance (that's why you only see getter methods like connectTimeoutMillis()). Instead, you need to use the Builder pattern to configure these settings before creating the client.
Here's a straightforward Kotlin example to set both connection and socket (read) timeouts:
import okhttp3.OkHttpClient import java.util.concurrent.TimeUnit // Configure timeouts using OkHttpClient.Builder val client = OkHttpClient.Builder() // Set connection timeout (time to establish a connection to the server) .connectTimeout(30, TimeUnit.SECONDS) // Set read timeout (time to wait for data after connection is established) .readTimeout(60, TimeUnit.SECONDS) // Optional: Set write timeout (time to wait for sending data) .writeTimeout(60, TimeUnit.SECONDS) // Build the final immutable OkHttpClient instance .build()
Key Notes:
OkHttpClientinstances are immutable once built, so all configuration (including timeouts) must happen during the builder phase.- If you already have an existing
OkHttpClientand want to adjust timeouts without reconfiguring everything else, usenewBuilder()to inherit the original client's settings:// Modify timeouts based on an existing client val updatedClient = client.newBuilder() .connectTimeout(45, TimeUnit.SECONDS) .readTimeout(90, TimeUnit.SECONDS) .build() - After building the client, you can still use methods like
client.connectTimeoutMillis()to retrieve the configured timeout values, just like you were doing before.
内容的提问来源于stack exchange,提问作者yahya




