You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  • OkHttpClient instances are immutable once built, so all configuration (including timeouts) must happen during the builder phase.
  • If you already have an existing OkHttpClient and want to adjust timeouts without reconfiguring everything else, use newBuilder() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:25:59