Httpclient 4.5.2 请求重试机制
程序员文章站
2022-03-03 22:21:19
重点是HttpRequestRetryHandler.retryRequest()方法 public static String callHttpServer(String contentType,String json, String url) { String result = ""; Clos ......
重点是httprequestretryhandler.retryrequest()方法
public static string callhttpserver(string contenttype,string json, string url) { string result = ""; closeablehttpclient httpclient = null; closeablehttpresponse response = null; try { httpclientbuilder httpclientbuilder = httpclients.custom(); httpclientbuilder.setretryhandler(new httprequestretryhandler() { @override public boolean retryrequest(ioexception arg0, int retrytimes, httpcontext arg2) { if (retrytimes > 3) { return false; } if (arg0 instanceof unknownhostexception || arg0 instanceof connecttimeoutexception || !(arg0 instanceof sslexception) || arg0 instanceof nohttpresponseexception) { return true; } httpclientcontext clientcontext = httpclientcontext.adapt(arg2); httprequest request = clientcontext.getrequest(); boolean idempotent = !(request instanceof httpentityenclosingrequest); if (idempotent) { return true; } return false; } }); httpclient = httpclientbuilder.build(); httppost httppost = new httppost(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(); } } } return result; }
更多参考:
上一篇: linux系统中su与sudo的用法
下一篇: Linux中手动释放缓存的方法