使用Apache HttpClient 4.x进行异常重试
在进行http请求时,难免会遇到请求失败的情况,失败后需要重新请求,尝试再次获取数据。
Apache的HttpClient提供了异常重试机制,在该机制中,我们可以很灵活的定义在哪些异常情况下进行重试。
重试前提
被请求的方法必须是幂等的:就是多次请求服务端结果应该是准确且一致的。
实现方式
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException; import javax.net.ssl.SSLException; import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; /**
* @author *
* @date 2017年5月18日 上午9:17:30
*
* @Description
*/
public class HttpPostUtils {
/**
*
* @param uri
* the request address
* @param json
* the request data that must be a JSON string
* @param retryCount
* the number of times this method has been unsuccessfully
* executed
* @param connectTimeout
* the timeout in milliseconds until a connection is established
* @param connectionRequestTimeout
* the timeout in milliseconds used when requesting a connection
* from the connection manager
* @param socketTimeout
* the socket timeout in milliseconds, which is the timeout for
* waiting for data or, put differently, a maximum period
* inactivity between two consecutive data packets
* @return null when method parameter is null, "", " "
* @throws IOException
* if HTTP connection can not opened or closed successfully
* @throws ParseException
* if response data can not be parsed successfully
*/
public String retryPostJson(String uri, String json, int retryCount, int connectTimeout,
int connectionRequestTimeout, int socketTimeout) throws IOException, ParseException {
if (StringUtils.isAnyBlank(uri, json)) {
return null;
} HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { @Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount > retryCount) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// An input or output transfer has been terminated
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host 修改代码让不识别主机时重试,实际业务当不识别的时候不应该重试,再次为了演示重试过程,执行会显示retryCount次下面的输出
System.out.println("不识别主机重试"); return true;
}
if (exception instanceof ConnectException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
}; CloseableHttpClient client = HttpClients.custom().setRetryHandler(httpRequestRetryHandler).build();
HttpPost post = new HttpPost(uri);
// Create request data
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
// Set request body
post.setEntity(entity); RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build();
post.setConfig(config);
// Response content
String responseContent = null;
CloseableHttpResponse response = null;
try {
response = client.execute(post, HttpClientContext.create());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
responseContent = EntityUtils.toString(response.getEntity(), Consts.UTF_8.name());
}
} finally {
if (ObjectUtils.anyNotNull(response)) {
response.close();
}
if (ObjectUtils.anyNotNull(client)) {
client.close();
}
}
return responseContent;
}
在实现的 retryRequest 方法中,遇到不识别主机异常,返回 true ,请求将重试。最多重试请求retryCount次。
使用Apache HttpClient 4.x进行异常重试的更多相关文章
- Apache HttpClient使用之阻塞陷阱
前言: 之前做个一个数据同步的定时程序. 其内部集成了某电商的SDK(简单的Apache Httpclient4.x封装)+Spring Quartz来实现. 原本以为简单轻松, 喝杯咖啡就高枕无忧的 ...
- 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类
推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...
- 论httpclient上传带参数【commons-httpclient和apache httpclient区别】
需要做一个httpclient上传,然后啪啪啪网上找资料 1.首先以前系统中用到的了commons-httpclient上传,找了资料后一顿乱改,然后测试 PostMethod filePost = ...
- Android 6.0删除Apache HttpClient相关类的解决方法
相应的官方文档如下: 上面文档的大致意思是,在Android 6.0(API 23)中,Google已经移除了Apache HttpClient相关的类,推荐使用HttpUrlConnection. ...
- android 中对apache httpclient及httpurlconnection的选择
在官方blog中,android工程师谈到了如何去选择apache client和httpurlconnection的问题: 原文见http://android-developers.blogspot ...
- org/apache/commons/pool/impl/GenericObjectPool异常的解决办法
org/apache/commons/pool/impl/GenericObjectPool异常的解决办法 webwork+spring+hibernate框架的集成, 一启动Tomcat服务器就出了 ...
- 新旧apache HttpClient 获取httpClient方法
在apache httpclient 4.3版本中对很多旧的类进行了deprecated标注,通常比较常用的就是下面两个类了. DefaultHttpClient -> CloseableHtt ...
- 基于apache httpclient 调用Face++ API
简要: 本文简要介绍使用Apache HttpClient工具调用旷世科技的Face API. 前期准备: 依赖包maven地址: <!-- https://mvnrepository.com/ ...
- 一个封装的使用Apache HttpClient进行Http请求(GET、POST、PUT等)的类。
一个封装的使用Apache HttpClient进行Http请求(GET.POST.PUT等)的类. import com.qunar.payment.gateway.front.channel.mp ...
随机推荐
- git 命令合并分支代码
git 命令合并分支代码 对于复杂的系统,我们可能要开好几个分支来开发,那么怎样使用git合并分支呢? 合并步骤: 1.进入要合并的分支(如开发分支合并到master,则进入master目录) git ...
- js画一棵树
用纯js画一棵树.思路: 1.一棵树的图片,作为页面背景: 2.通过html5中的canvas画布进行遮罩: 3.定时每隔10ms,从下往上清除1px的遮罩: <!DOCTYPE html> ...
- 基于netcore对ElasitSearch客户端NEST查询功能的简单封装NEST.Repository
NEST.Repository A simple encapsulation with NEST client for search data form elasticsearch. github A ...
- CSS知多少
1.Cascading Style Sheets 层叠样式表 2.层叠就是浏览器对多个样式来源进行叠加,最终确定结果的过程. 3. 样式的5大来源:浏览器默认样式.浏览器用户自定义样式.行内样式.内部 ...
- <Android 应用 之路> 百度地图API使用(4)
前言 百度地图的定位功能和基础地图功能是分开的,使用的是另外的jar包和so库文件,详情请关注官网: 百度定位SDK 配置 下载对应的jar包和so库,然后移动到lib目录下 AS中注意事项 sour ...
- js获取日期:昨天今天和明天、后天 [转贴记录]
<html> <head> <meta http-equiv="Content-Type" content="textml; charset ...
- 客户端和服务端如何使用Token和Session
一.我们先解释一下他的含义: 1.Token的引入:Token是在客户端频繁向服务端请求数据,服务端频繁的去数据库查询用户名和密码并进行对比,判断用户名和密码正确与否,并作出相应提示,在这样的背 ...
- 为什么说对象字面量赋值比new Object()高效?
http://www.cnblogs.com/mushishi/p/5811743.html
- Django 的视图层
什么是视图: 之前我们也了解了urls路由 那么路由的主要作用是决定你下一步走哪个视图函数 ,视图就是用来存放一个个的函数的python文件,主要存储的函数就是你Django主要的流程的控制 都存放在 ...
- 面向对象进阶------>模块 json pickle hashlib
何为模块呢? 其实模块就是.py文件 python之所以好用就是模块多 模块分三种 : 内置模块 . 拓展模块.自定义模块. 现在我们来认识:内置模块中的 序列化模块和 hashlib 模块 1 ...