How to set connection timeout with OkHttp

后端 未结 11 876
一向
一向 2020-11-27 10:32

I am developing app using OkHttp library and my trouble is I cannot find how to set connection timeout and socket timeout.

OkHttpClient client = new OkHttpCl         


        
11条回答
  •  爱一瞬间的悲伤
    2020-11-27 10:41

    OkHttp Version:3.11.0 or higher

    From okhttp source code:

    /**
     * Sets the default connect timeout for new connections. A value of 0 means no timeout,
     * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to
     * milliseconds.
     *
     * 

    The connectTimeout is applied when connecting a TCP socket to the target host. * The default value is 10 seconds. */ public Builder connectTimeout(long timeout, TimeUnit unit) { connectTimeout = checkDuration("timeout", timeout, unit); return this; }

    unit can be any value of below

    TimeUnit.NANOSECONDS
    TimeUnit.MICROSECONDS
    TimeUnit.MILLISECONDS
    TimeUnit.SECONDS
    TimeUnit.MINUTES
    TimeUnit.HOURS
    TimeUnit.DAYS
    

    example code

    OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(5000, TimeUnit.MILLISECONDS)/*timeout: 5 seconds*/
        .build();
    
    String url = "https://www.google.com";
    Request request = new Request.Builder()
        .url(url)
        .build();
    
    try {
        Response response = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    Updated

    I have add new API to OkHttp from version 3.12.0, you can set timeout like this:

    OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(Duration.ofSeconds(5)) // timeout: 5 seconds
        .build();
    

    NOTE: This requires API 26+ so if you support older versions of Android, continue to use (5, TimeUnit.SECONDS).

提交回复
热议问题