如何使用OkHttp设置连接超时

时间:2014-09-20 22:16:07

标签: java timeout okhttp

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

OkHttpClient client = new OkHttpClient();

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

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

11 个答案:

答案 0 :(得分:284)

你只需要这样做

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中设置的值是setSoTimeout Connection类内部Socket OkHttp中使用的值。

未在OkHttpClient设置任何超时相当于在0setConnectTimeout上设置setReadTimeout的值,并且根本不会导致超时。可以找到说明here

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

自版本2.5.0起,读/写/连接超时值默认设置为10秒,如@ChristerNordvik所述。这可以看作here

从OkHttp3开始,现在可以通过Builder这样做

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

您还可以查看食谱here

答案 1 :(得分:120)

对于okhttp3,这已经改变了一点。

现在您使用构建器设置时间,而不是设置器,如下所示:

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

更多信息可以在他们的维基中找到: https://github.com/square/okhttp/wiki/Recipes#timeouts

答案 2 :(得分:11)

对于Retrofit改装: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();

答案 3 :(得分: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();

答案 4 :(得分: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 :(得分: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();

答案 6 :(得分: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();

答案 7 :(得分: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();

答案 8 :(得分:4)

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();
}

已更新

我已经从3.12.0版本向okhttp添加了新的api,您可以这样设置超时时间:

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

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

答案 9 :(得分:2)

如果要自定义配置,请先使用以下方法创建OKhttpclient,然后在其上添加构建器。

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);
    }

答案 10 :(得分:0)

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

val client = OkHttpClient().newBuilder().callTimeout(CALL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES).build()