下载图片场景
okhttp设置了读超时事件,但是从日志来看好像没有生效,而且正好是默认的10s,都消耗在了response.body().bytes()。
private static final ConnectionPool mConnectionPool = new ConnectionPool(connectionPoolSize, 30, TimeUnit.MINUTES);
public static OkHttpClient getHttpClient(int timeout, EventListener listener) {
return new OkHttpClient.Builder()
.followRedirects(false)
.retryOnConnectionFailure(false)
.connectTimeout(2000, TimeUnit.MILLISECONDS) //连接超时
.readTimeout(timeout, TimeUnit.MILLISECONDS) //读取超时
//ThreadPoolExecutor(0, 2147483647, 60L, TimeUnit.SECONDS, new SynchronousQueue(), Util.threadFactory("OkHttp ConnectionPool", true));
.connectionPool(mConnectionPool)
.eventListener(listener)
.build();
}
public static byte[] downloadFileWithOKHttpClient(String url, int timeoutSecond) throws IOException {
OKHttpClientEventListener listener = new OKHttpClientEventListener();
OkHttpClient client = getHttpClient(timeoutSecond * 1000, listener);
Request request = new Request.Builder()
//访问路径
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
long l = response.body().contentLength();
byte[] bytes = response.body().bytes();
return bytes;
} else {
throw new RuntimeException();
}
}
}
public static void main(String[] args) throws IOException {
downloadFileWithOKHttpClient("",5);
}
log:
14:33:52.471 callStart
14:33:52.472 dnsStart
14:33:52.472 dnsEnd
14:33:52.472 connectStart
14:33:52.504 secureConnectStart
14:33:52.664 secureConnectEnd
14:33:52.665 connectEnd
14:33:52.665 connectionAcquired
14:33:52.665 requestHeadersStart
14:33:52.665 requestHeadersEnd
14:33:52.665 responseHeadersStart
14:33:52.828 responseHeadersEnd
14:33:52.828 responseBodyStart
14:34:02.162 responseBodyEnd
14:34:02.162 connectionReleased
14:34:02.162 callEnd