importorg.apache.commons.lang3.StringUtils;importorg.apache.http.Consts;importorg.apache.http.HttpStatus;importorg.apache.http.ParseException;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.client.protocol.HttpClientContext;importorg.apache.http.entity.ContentType;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;importjava.io.IOException;publicclassHttpPostUtils{
/**
* @param uri the request address
* @param json the request data that must be a JSON string
* @throws IOException if HTTP connection can not opened or closed successfully
* @throws ParseException if response data can not be parsed successfully
*/publicStringretryPostJson(String uri,String json)throwsIOException,ParseException{
if(StringUtils.isAnyBlank(uri, json)){
returnnull;}// 构建HttpClientCloseableHttpClient client =HttpClients.custom().setRetryHandler(newRetryHandler()).build();// 构建请求HttpPost httpPost =newHttpPost(uri);// 设置请求体StringEntity entity =newStringEntity(json,ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);// 设置超时时间RequestConfig config =RequestConfig.custom().setConnectionRequestTimeout(5000)// 超5秒还没返回新的可用链接,抛ConnectionPoolTimeoutException。默认值为0,表示无限等待。.setConnectTimeout(5000)// 超5秒还没建立链接,抛ConnectTimeoutException。默认值为0,表示无限等待。.setSocketTimeout(5000)// 超5秒还没返回数据,抛SocketTimeoutException。默认值为0,表示无限等待。.build();
httpPost.setConfig(config);// ResponseCloseableHttpResponse response =null;String responseContent =null;try{
response = client.execute(httpPost,HttpClientContext.create());if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
responseContent =EntityUtils.toString(response.getEntity(),Consts.UTF_8.name());}}finally{
if(response !=null){
response.close();}if(client !=null){
client.close();}}return responseContent;}}
失败重试机制
importorg.apache.http.HttpEntityEnclosingRequest;importorg.apache.http.HttpRequest;importorg.apache.http.NoHttpResponseException;importorg.apache.http.client.HttpRequestRetryHandler;importorg.apache.http.client.protocol.HttpClientContext;importorg.apache.http.conn.ConnectTimeoutException;importorg.apache.http.protocol.HttpContext;importjavax.net.ssl.SSLException;importjavax.net.ssl.SSLHandshakeException;importjava.io.IOException;importjava.io.InterruptedIOException;importjava.net.ConnectException;importjava.net.UnknownHostException;publicclassRetryHandlerimplementsHttpRequestRetryHandler{
@OverridepublicbooleanretryRequest(IOException exception,int executionCount,HttpContext context){
if(executionCount >=2){
// 如果已经重试了2次,就放弃// Do not retry if over max retry countreturnfalse;}if(exception instanceofNoHttpResponseException){
// 如果服务器丢掉了连接,那么就重试returntrue;}if(exception instanceofSSLHandshakeException){
// 不要重试SSL握手异常returnfalse;}if(exception instanceofSSLException){
// SSL握手异常// SSL handshake exceptionreturnfalse;}if(exception instanceofConnectTimeoutException){
// 连接被拒绝returnfalse;}if(exception instanceofInterruptedIOException){
// An input or output transfer has been terminated// 超时returnfalse;}if(exception instanceofUnknownHostException){
// Unknown host 修改代码让不识别主机时重试,实际业务当不识别的时候不应该重试,再次为了演示重试过程,执行会显示retryCount次下面的输出// 目标服务器不可达System.out.println("不识别主机重试");returntrue;}if(exception instanceofConnectException){
// Connection refusedreturnfalse;}HttpClientContext clientContext =HttpClientContext.adapt(context);HttpRequest request = clientContext.getRequest();if(!(request instanceofHttpEntityEnclosingRequest)){
// Retry if the request is considered idempotentreturntrue;}returnfalse;}}
模拟解析返回的Json串
public static List<User>parserJsonToUser(){
// 模拟返回的Json串
Map<String, List<String>> map = new HashMap<>();
map.put("name", Arrays.asList("name1","name2","name3"));
map.put("age", Arrays.asList("11","23","23"));
map.put("num", Arrays.asList("123","234","345"));
String json1 = JsonUtils.toJson(map);
System.out.println(json1);// fastjson
JSONObject jsonObject = JSON.parseObject(json1, Feature.OrderedField);// 返回的属性
List<String> fields = new ArrayList<>(map.keySet());// 几份值int size = jsonObject.getJSONArray(fields.get(0)).size();
List<User> users = new ArrayList<>();for(int i =0; i < size; i++){
User user1 = new User();for(String field : fields){
Object value = jsonObject.getJSONArray(field).get(i);
ReflectUtils.setFieldValue(user1, field, value);}
users.add(user1);}
System.out.println(users);return users;}
结果
{
"num":["123","234","345"],"name":["name1","name2","name3"],"age":["11","23","23"]}[HttpPostUtils.User(name=name1, age=11, num=123), HttpPostUtils.User(name=name2, age=23, num=234), HttpPostUtils.User(name=name3, age=23, num=345)]