如何设置OkHttp连接超时

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

OkHttpClient client = new OkHttpClient();


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


Response response = client.newCall(request).execute();
161192 次浏览

OkHttp3开始,你可以通过构建器这样做

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

你也可以查看配方在这里

对于旧版本,您只需这样做

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

OkHttpClient上不设置任何超时等同于在setConnectTimeoutsetReadTimeout上设置0的值,并且根本不会导致超时。描述可以找到在这里

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

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

对于Retrofit 2.0.0-beta1beta2,代码如下:

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

对于okhttp3,这有一点变化。

现在你使用构建器而不是setter来设置时间,就像这样:

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

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

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

像这样:

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

添加gradle文件和同步项目:

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.6.2'

在Java类中添加:

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

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

okhttp: 3.9.0开始,代码如下:

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

这招对我很管用:

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

来源:https://github.com/square/okhttp/issues/3553

如果您想自定义配置,那么请使用下面的方法先创建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);
}

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版本添加了新的API到OkHttp,你可以像这样设置超时:

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

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

您可以设置调用超时来覆盖从解析DNS、连接、写入请求体、服务器处理到读取响应体的整个周期。

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