我想知道我应该为我的改装客户设置多少秒。
答案 0 :(得分:64)
改进代码段:(如果您不提供OkHttpClient):
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
OkHttp代码段:
connectTimeout = 10_000;
readTimeout = 10_000;
writeTimeout = 10_000;
他们使用不同的值。例如,对于他们使用的feedback相关:
public class FeedbackConstants{
public static final int FEEDBACK_CONNECT_TIMEOUT_MS = 15000;
public static final int FEEDBACK_READ_TIMEOUT_MS = 15000;
public static final int GOOGLE_API_CLIENT_CONNECTION_TIMEOUT_S = 10;
}
他们正在使用Volley和你can take a look在某些超时时间。是的,他们看起来很短。
/** The default socket timeout in milliseconds */
public static final int DEFAULT_TIMEOUT_MS = 2500;
在different http client中,他们会为您提供一些线索,说明他们认为这是短暂合理的短暂超时。
/**
* Default 2s, deliberately short. If you need longer, you should be using
* {@link AsyncHttpClient} instead.
*/
protected int connectionTimeout = 2000;
/**
* Default 8s, reasonably short if accidentally called from the UI thread.
*/
protected int readTimeout = 8000;
答案 1 :(得分:22)
来源:
OkHttpClient defaultClient() {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(15, TimeUnit.SECONDS);
client.setReadTimeout(15, TimeUnit.SECONDS);
client.setWriteTimeout(15, TimeUnit.SECONDS);
return client;
}
答案 2 :(得分:0)
您可以使用
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.build();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:3000/")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create());
有关更多详细信息,请访问:https://futurestud.io/tutorials/retrofit-2-customize-network-timeouts
答案 3 :(得分:0)
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/OkHttpClient.kt#L471
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/OkHttpClient.kt#L203
internal var connectTimeout = 10_000
internal var readTimeout = 10_000
internal var writeTimeout = 10_000
答案 4 :(得分:-1)
我在我的RetrofitApiClient中使用它。 okhttp版本3.4.1
public class RetrofitApiClient {
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15L, TimeUnit.SECONDS)
.writeTimeout(15L, TimeUnit.SECONDS);
public void someMethod() {
OkHttpClient client = httpClient.build();
}
}