java httpclient4.5_Httpclient4.5.x使用重试机制

public staticString callHttpServer(String contentType,String json, String url) {

String result= "";

CloseableHttpClient httpclient= null;

CloseableHttpResponse response= null;try{HttpClientBuilder httpClientBuilder=HttpClients.custom();

httpClientBuilder.setRetryHandler(newHttpRequestRetryHandler() {

@Overridepublic boolean retryRequest(IOException arg0, intretryTimes, HttpContext arg2) {if (retryTimes > 3) {return false;

}if (arg0 instanceof UnknownHostException || arg0 instanceofConnectTimeoutException|| !(arg0 instanceof SSLException) || arg0 instanceofNoHttpResponseException) {return true;

}

HttpClientContext clientContext=HttpClientContext.adapt(arg2);

HttpRequest request=clientContext.getRequest();boolean idempotent = !(request instanceofHttpEntityEnclosingRequest);if(idempotent) {

return true;

}return false;

}

});

httpclient=httpClientBuilder.build();

HttpPost httppost= newHttpPost(url);

httppost.setHeader("Content-Type", contentType);

httppost.setHeader("Expect", "100-continue");

httppost.setHeader("Accept-Encoding", "gzip,deflate");

httppost.setHeader("Connection", "Keep-Alive");//如果json 为null,会出现异常

if (null !=json) {

StringEntity stringEntity= new StringEntity(json, "utf-8");

stringEntity.setContentEncoding("UTF-8");

stringEntity.setContentType("application/json");

httppost.setEntity(stringEntity);

}

response=httpclient.execute(httppost);

HttpEntity entity=response.getEntity();if (entity != null) {int status =response.getStatusLine().getStatusCode();if ((status >= 200 && status < 300)) {

result=EntityUtils.toString(entity);}else{

result= null;}

}

}catch(Exception ex) {

logger.error("call http service error:{}", ex);

result= null;

ex.printStackTrace();

}finally{if (null !=response) {try{

response.close();

}catch(IOException e) {

logger.error("call http service response close error:{}", e);

e.printStackTrace();

}

}

}returnresult;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值