如何使用OkHttp设置连接超时


173

我正在使用OkHttp库开发应用程序,但我的麻烦是我找不到如何设置连接超时和套接字超时的方法。

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder().url(url).build();

Response response = client.newCall(request).execute();

2
您选择的答案不再有效。也许您应该编辑问题以指定okhttp的版本。
Theyouthis

Answers:


324

您只需要这样做

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(15, TimeUnit.SECONDS);    // socket timeout

Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();

要知道,值设置setReadTimeout为使用的一个setSoTimeoutSocket的内部OkHttp Connection类。

在上不设置任何超时OkHttpClient等同于将值设置为0on setConnectTimeout或,setReadTimeout并且将导致完全没有超时。描述可以在这里找到。

如@marceloquinta在评论中提到的,setWriteTimeout也可以设置。

从2.5.0版本开始,读/写/连接超时值默认设置为10秒,如@ChristerNordvik所述。这可以在这里看到。

从OkHttp3开始,现在可以像这样通过Builder进行此操作

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

您也可以在这里查看食谱。


6
是否可以为每个请求设置不同的超时时间(每个请求具有相同的静态客户端)?
StErMi 2014年

3
您可以为每个请求设置特定的超时时间:以下是一些信息:github.com/square/okhttp/wiki/Recipes
Tobliug

3
不要忘记WRITE超时:client.setWriteTimeout(10,TimeUnit.SECONDS);
marceloquinta 2015年

7
@MiguelLavigne仅供参考,OkHttp在2.5.0中进行了更改,默认超时为10秒。
Christer Nordvik

5
过时的答案
devDeejay


12

对于翻新改造:2.0.0-beta4,代码如下:

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

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://api.yourapp.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();

9

对于Retrofit 2.0.0-beta1或beta2,代码如下

    OkHttpClient client = new OkHttpClient();

    client.setConnectTimeout(30, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    client.setWriteTimeout(30, TimeUnit.SECONDS);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://api.yourapp.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

7
//add in gradle and sync
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.6.2'

import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;


Builder b = new Builder();
b.readTimeout(200, TimeUnit.MILLISECONDS);
b.writeTimeout(600, TimeUnit.MILLISECONDS);
// set other properties

OkHttpClient client = b.build();

5

现在改变了。替换.Builder().newBuilder()

okhttp:3.9.0开始,代码如下:

OkHttpClient okHttpClient = new OkHttpClient()
    .newBuilder()
    .connectTimeout(10,TimeUnit.SECONDS)
    .writeTimeout(10,TimeUnit.SECONDS)
    .readTimeout(30,TimeUnit.SECONDS)
    .build();

5

okhttp版本:3.11.0或更高

来自okhttp源代码

/**
 * Sets the default connect timeout for new connections. A value of 0 means no timeout,
 * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to
 * milliseconds.
 *
 * <p>The connectTimeout is applied when connecting a TCP socket to the target host.
 * The default value is 10 seconds.
 */
public Builder connectTimeout(long timeout, TimeUnit unit) {
  connectTimeout = checkDuration("timeout", timeout, unit);
  return this;
}

unit 可以是以下任何值

TimeUnit.NANOSECONDS
TimeUnit.MICROSECONDS
TimeUnit.MILLISECONDS
TimeUnit.SECONDS
TimeUnit.MINUTES
TimeUnit.HOURS
TimeUnit.DAYS

示例代码

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(5000, TimeUnit.MILLISECONDS)/*timeout: 5 seconds*/
        .build();

String url = "https://www.google.com";
Request request = new Request.Builder()
        .url(url)
        .build();

try {
    Response response = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}

更新

我已经从version将新的api添加到okhttp 3.12.0,您可以这样设置超时:

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(Duration.ofSeconds(5))/*timeout: 5 seconds*/
        .build();

注意:这需要API 26+,因此,如果您支持旧版本的Android,请继续使用(5, TimeUnit.SECONDS)


4

像这样:

//New Request
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
        final OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();

4

这对我有用...来自https://github.com/square/okhttp/issues/3553

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .retryOnConnectionFailure(false) <-- not necessary but useful!
        .build();

2

如果要定制配置,请使用以下方法首先创建OKhttpclient,然后在其顶部添加builder。

private final OkHttpClient client = new OkHttpClient();

// Copy to customize OkHttp for this request.
    OkHttpClient client1 = client.newBuilder()
        .readTimeout(500, TimeUnit.MILLISECONDS)
        .build();
    try (Response response = client1.newCall(request).execute()) {
      System.out.println("Response 1 succeeded: " + response);
    } catch (IOException e) {
      System.out.println("Response 1 failed: " + e);
    }

1

您可以设置一个呼叫超时,以覆盖从解析DNS,连接,编写请求正文,服务器处理以及读取响应正文的整个周期。

val client = OkHttpClient().newBuilder().callTimeout(CALL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES).build()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.