OkHttp3超时设置和超时异常捕获

OkHttp3超时设置

已经不能在 OkHttp3中使用的方法

为了容错和更好的用户体验,必须为OkHttp设置超时。

上网找了半天,只找到下面的代码。注意它们不能在 OkHttp3中使用

public ConfigureTimeouts() throws Exception {
  client = new OkHttpClient();
  client.setConnectTimeout(10, TimeUnit.SECONDS);
  client.setWriteTimeout(10, TimeUnit.SECONDS);
  client.setReadTimeout(30, TimeUnit.SECONDS);
}


以上代码中的方法setConnectTimeout,在OkHttp3中根本就不存在。


OkHttp3中设置超时的方法

上官网查资料,找到了新的方法

见网址:http://square.github.io/okhttp/3.x/okhttp/

Method Detail

connectTimeout

public OkHttpClient.Builder connectTimeout(long timeout,
TimeUnit unit)

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

readTimeout

public OkHttpClient.Builder readTimeout(long timeout,
TimeUnit unit)

Sets the default read timeout for new connections. A value of 0 means no timeout, otherwise values must be between 1 and Integer.MAX_VALUE when converted to milliseconds.

writeTimeout

public OkHttpClient.Builder writeTimeout(long timeout,
TimeUnit unit)

Sets the default write timeout for new connections. A value of 0 means no timeout, otherwise values must be between 1 and Integer.MAX_VALUE when converted to milliseconds.

从上面可以看到设置超时移到了OkHttpClient.Builder中,所以最新的设置超时的代码如下:

    public WebApi(){
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
    }

捕获OkHttp3超时

然后捕获异常,加以处理。

    public void GetServersList(IServersListEvent serversListEvent) {
        this.serversListEvent = serversListEvent;
        serversLoadTimes = 0;
        Request request = new Request.Builder()
                .url(serversListUrl)
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                if(e.getCause().equals(SocketTimeoutException.class) && serversLoadTimes


你可能感兴趣的:(OkHttp3,超时设置,超时异常捕获,Android,JAVA)