通常,我们为 okHttp 客户端设置超时,并使用该客户端的单个实例。因此,一旦生成该客户端,我们就无法更改该客户端的超时时间。
如何更改特定请求的超时时间?有吗
在不创建新客户的情况下做到这一点?
某些调用在每个应用程序中花费至少 1/2 的时间是很常见的,这比其他调用需要更多的超时时间。如果请求可以覆盖默认超时,那就太好了。
最佳答案
在 3.9 中,可以在拦截器中设置每个请求
https://github.com/square/okhttp/blob/36bd68aa3e93affb12504cd40454e64c6812019c/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java#L747-L757
@Test public void chainWithReadTimeout() throws Exception {
Interceptor interceptor1 = new Interceptor() {
@Override public Response intercept(Chain chainA) throws IOException {
assertEquals(5000, chainA.readTimeoutMillis());
Chain chainB = chainA.withReadTimeout(100, TimeUnit.MILLISECONDS);
assertEquals(100, chainB.readTimeoutMillis());
return chainB.proceed(chainA.request());
}
};
}
关于okhttp3 - 如何在okhttp中更改请求的超时时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46845206/