OKHTTP3设置Timeout参数无效
在使用okhttp3发送请求,用IP直接访问时,设置的超时时间是正常的.改成访问某个域名时,设置的超时时间是10s,但是实际测试是40s左右,程序才打印出错误信息.
解决方法:
自己实现一个okhttp3.Dns的类,处理域名解析超时问题.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit;
import okhttp3.Dns; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;
public class GetAccuTime { public void getContent(Callback callback) { new Thread(() -> { try { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10 , TimeUnit.SECONDS) .writeTimeout(10 ,TimeUnit.SECONDS) .readTimeout(10 ,TimeUnit.SECONDS) .dns(new XDns(10,TimeUnit.SECONDS)) .build(); Request request = new Request.Builder() .url("https://www.pengwf.com/") .build(); Response response = client.newCall(request).execute(); String res = response.body().string(); callback.onResponse(res); } catch (Exception e) { callback.onError(e); } }).start(); }
public interface Callback{ void onResponse(String content); void onError(Exception e); }
public class XDns implements Dns { private long timeout; private TimeUnit unit;
public XDns(long timeout, TimeUnit unit) { this.timeout = timeout; this.unit = unit; }
@Override public List<InetAddress> lookup(final String hostname) throws UnknownHostException { if (hostname == null) { throw new UnknownHostException("hostname == 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, unit); } catch (Exception var4) { UnknownHostException unknownHostException = new UnknownHostException("Broken system behaviour for dns lookup of " + hostname); unknownHostException.initCause(var4); throw unknownHostException; } } } } }
|