最近程序在回调请求的时候,遇到httpClient请求异常的情况,有时可以,有时异常。添加超时时间和失败重连机制处理。记录一下。
RequestConfig
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setStaleConnectionCheckEnabled(true)
.build();
这个超时可以设置为客户端级别,作为所有请求的默认值:
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultRequestConfig(defaultRequestConfig)
.build();
Request不会继承客户端级别的请求配置,所以在自定义Request的时候,需要将客户端的默认配置拷贝过去:
HttpGet httpget = new HttpGet("http://www.apache.org/");
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
.setProxy(new HttpHost("myotherproxy", 8080))
.build();
httpget.setConfig(requestConfig);
封装sendPost请求:
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param params 请求参数
* @param charset 字符集
* @param headers 头部信息
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String, Object> params, String charset, Map<String, String> headers) {
StringBuffer resultBuffer;
HttpClient client;
BufferedReader br = null;
try {
if (url.startsWith("https://")) {
client = new SslClient();
} else {
client = new DefaultHttpClient();
}
HttpPost httpPost = new HttpPost(url);
// 设置超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000)
.setSocketTimeout(5000).build();
httpPost.setConfig(requestConfig);
// 构建请求参数
List<NameValuePair> list = new ArrayList<>();
Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> elem = iterator.next();
if (elem.getValue() != null) {
list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
}
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
HttpResponse response = client.execute(httpPost);
// 读取服务器响应数据
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
}
setConnectTimeout:设置连接超时时间,单位毫秒。
setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
参考资料:
http://blog.csdn.net/zheng0518/article/details/46469051
https://segmentfault.com/a/1190000000587944
http://my.oschina.net/wallechen/blog/526642