okhttp

How to change timeout for a request in 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.

How to change the timeout for a particular request ?? Is there anyway to do it without creating new client??

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.


Solution

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