如何在okhttp中更改请求的超时时间

问题描述:

通常,我们为 okHttp 客户端设置超时,并使用该客户端的单个实例.因此,一旦生成该客户端,我们就无法更改该客户端的超时时间.

In general we set timeout for the okHttp client and we use single instance of that client. So, we can't change the timeout for that client once it's generated.

如何更改特定请求的超时时间??有吗在不创建新客户的情况下做到这一点?

有些调用在每个应用中花费至少 1/2 的时间是很常见的,这比其他调用需要更多的超时时间.如果请求可以覆盖默认超时,那就太好了.

It's very common that some calls take more time atleast 1/2 per app, which needs more timeout than others. it would be great if request can override the default timeout.

在 3.9 中,可以在拦截器中为每个请求设置此项

In 3.9 it is possible to set this per request in an interceptor

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