天天看點

OkHttp設定逾時時間

在使用okHttp的時候我們經常會使用逾時設定:如下:

okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .dns(new xDns(5))
                .build();      

但是在某些情況下,eg:域名解析不了。我們設定的這些逾時值不管用,往往需要幾十秒之後get/post之後才傳回錯誤。是以此時我們就需要設定一下dns解析逾時,關于okhttp的dns解析逾時網上很多方法,這裡我使用最簡答的:okhttp.dns接口:

public class xDns implements Dns {
    private long timeout  = 5;

    public xDns(long timeout){
        this.timeout = timeout;
    }

    @Override
    public List<InetAddress> lookup(String hostname) throws UnknownHostException {
        if(hostname == null){
            throw new UnknownHostException("host name is null");
        }
        else{
            try {
                FutureTask<List<InetAddress>> task = new FutureTask<>(
                        new Callable<List<InetAddress>>() {
                            @Override
                            public List<InetAddress> call() throws Exception {
                                return Arrays.asList(InetAddress.getAllByName(hostname));
                            }
                        });
                new Thread(task).start();
                return task.get(timeout, TimeUnit.SECONDS);
            } catch (Exception var4) {
                UnknownHostException unknownHostException =
                        new UnknownHostException("Unable to resolve host " + hostname);
                unknownHostException.initCause(var4);
                throw unknownHostException;
            }
        }
    }
}