如果客户端在一定时间内未能响应,则OkHttp取消请求

时间:2018-10-08 17:37:01

标签: java okhttp3 okhttp

我在Java应用程序中使用OkHttp客户端,并且正在调用我的一个客户端,但是由于某些问题,由于客户端的服务速度很慢并且我的请求正在排队,这正在造成瓶颈。如果客户端在一定时间内没有响应,有没有办法取消请求?

1 个答案:

答案 0 :(得分:0)

您可以创建OkHttp客户端构建器,设置超时值,如下所示。

     final OkHttpClient.Builder clientBuilder = 
     getHttpClientBuilder(RetrofitLogger.Level.BODY);
     Retrofit.Builder builder = new Retrofit.Builder();
     builder.baseUrl(<BASE URL>);
     builder.client(clientBuilder.build());



     public Builder getHttpClientBuilder() {
        final Builder builder = new Builder();
          if (shortTimeout) {
            builder.readTimeout(SHORT_TIMEOUT, TimeUnit.SECONDS);
            builder.connectTimeout(SHORT_TIMEOUT, TimeUnit.SECONDS);
             builder.retryOnConnectionFailure(false);
           }
        else {
          builder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
           builder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
        }
        builder.connectionPool(new ConnectionPool(IDLE_CONNECTIONS, IDLE_TIMEOUT, 
        TimeUnit.SECONDS));
        return builder;
      }