[英]How to set connection timeout with OkHttp
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();
As of OkHttp3 you can do this through the Builder like 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 .您还可以在此处查看食谱。
For older versions, 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 setReadTimeout
is the one used in setSoTimeout
on the Socket
internally in the OkHttp
Connection
class.要知道,在值集
setReadTimeout
是在使用一个setSoTimeout
上的Socket
的内部OkHttp
Connection
类。
Not setting any timeout on the OkHttpClient
is the equivalent of setting a value of 0
on setConnectTimeout
or setReadTimeout
and will result in no timeout at all.不在
OkHttpClient
上设置任何超时相当于在setConnectTimeout
或setReadTimeout
上设置值0
, setConnectTimeout
setReadTimeout
不会导致超时。 Description can be found here .可以在此处找到说明。
As mentioned by @marceloquinta in the comments setWriteTimeout
can 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.如@ChristerNordvik 所述,从
2.5.0
版开始,读取/写入/连接超时值默认设置为 10 秒。 This can be seen here .这可以在这里看到。
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
For Retrofit retrofit:2.0.0-beta4
the code goes as follows:对于 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();
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();
Adding in gradle file and sync project :添加 gradle 文件和同步项目:
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.6.2'
Adding in Java class:在 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();
OkHttp Version: 3.11.0
or 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;
}
unit
can 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();
}
I have add new API to OkHttp from version 3.12.0
, you can set timeout like this:我从版本
3.12.0
向OkHttp添加了新的 API,您可以像这样设置超时:
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)
。
It's changed now.现在已经改变了。 Replace
.Builder()
with .newBuilder()
用
.Builder()
替换.newBuilder()
As of okhttp:3.9.0 the 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();
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();
This worked for me:这对我有用:
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.retryOnConnectionFailure(false) <-- not necessary but useful!
.build();
Source: https://github.com/square/okhttp/issues/3553来源: https : //github.com/square/okhttp/issues/3553
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);
}
您可以设置调用超时以涵盖从解析 DNS、连接、写入请求正文、服务器处理和读取响应正文的整个周期。
val client = OkHttpClient().newBuilder().callTimeout(CALL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES).build()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.