HttpClient如何使用RequestConfig设置连接超时,请求超时,读取超时呢?
下文笔者讲述HttpClient中设置各种超时的方法分享,如下所示
未设置超时前的方法
public static HttpResponse doGet(String host, String path,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host,path);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
设置超时后的方法
public static HttpResponse doGet(String host, String path,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host,path);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
request.setConfig(setTimeOutConfig(request.getConfig()));
return httpClient.execute(request);
}
/**
* 设置 连接超时、 请求超时 、 读取超时 毫秒
* @param requestConfig
* @return
*/
private static RequestConfig setTimeOutConfig(RequestConfig requestConfig){
return RequestConfig.copy(requestConfig)
.setConnectionRequestTimeout(60000)
.setConnectTimeout(60000)
.setSocketTimeout(10000)
.build();
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


