如何在okhttp中更改请求的超时时间 [英] How to change timeout for a request in okhttp

查看:194
本文介绍了如何在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());
      }
    };
  }

这篇关于如何在okhttp中更改请求的超时时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆