Java 如何使用 OkHttp 设置连接超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25953819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:35:19  来源:igfitidea点击:

How to set connection timeout with OkHttp

javatimeoutokhttp

提问by kelvincer

I am developing app using OkHttp library and my trouble is I cannot find how to set connection timeout and socket timeout.

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

OkHttpClient client = new OkHttpClient();

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

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

采纳答案by Miguel Lavigne

You simply have to do this

你只需要这样做

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

Be aware that value set in setReadTimeoutis the one used in setSoTimeouton the Socketinternally in the OkHttpConnectionclass.

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

Not setting any timeout on the OkHttpClientis the equivalent of setting a value of 0on setConnectTimeoutor setReadTimeoutand will result in no timeout at all. Description can be found here.

不设置任何超时OkHttpClient相当于设置一个值0on setConnectTimeoutorsetReadTimeout并且根本不会导致超时。可以在此处找到说明。

As mentioned by @marceloquinta in the comments setWriteTimeoutcan also be set.

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

As of version 2.5.0 read / write / connect timeout values are set to 10 seconds by default as mentioned by @ChristerNordvik. This can be seen here.

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

As of OkHttp3 can now do this through the Builderlike so

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

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

You can also view the recipe here.

您还可以在此处查看食谱。

回答by xaxist

For Retrofit 2.0.0-beta1 or beta2, the code goes as follows

对于 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();

回答by Kaizie

For okhttp3 this has changed a bit.

对于 okhttp3,这已经发生了一些变化。

Now you set up the times using the builder, and not setters, like this:

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

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

More info can be found in their wiki: https://github.com/square/okhttp/blob/b3dcb9b1871325248fba917458658628c44ce8a3/docs/recipes.md#timeouts-kt-java

更多信息可以在他们的 wiki 中找到:https: //github.com/square/okhttp/blob/b3dcb9b1871325248fba917458658628c44ce8a3/docs/recipes.md#timeouts-kt-java

回答by Sam

For Retrofit retrofit:2.0.0-beta4 the code goes as follows

对于 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();

回答by Joolah

like so:

像这样:

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

回答by Mohammad nabil

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

回答by Leo

It's changed now. Replace .Builder()with .newBuilder()

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

As of okhttp:3.9.0the code goes as follows:

okhttp:3.9.0 开始,代码如下:

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

回答by rHenderson

this worked for me ... from https://github.com/square/okhttp/issues/3553

这对我有用......来自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();

回答by sandhya murugesan

If you want to customize the configuration then use the below methodology of creating OKhttpclient first and then add builder on top of it.

如果要自定义配置,请使用以下方法先创建 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);
    }

回答by shellhub

okhttp version:3.11.0or higher

okhttp 版本:3.11.0或更高

from okhttp source code

来自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;
}

unitcan be any value of below

unit可以是以下的任何值

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

example code

示例代码

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

Updated

更新

I have add new api to okhttp from version 3.12.0, you can set timeout like this:

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

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

NOTE:This requires API 26+ so if you support older versions of Android, continue to use (5, TimeUnit.SECONDS).

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