本人在使用httpclient作接口测试的过程当中,以前并无考虑到请求失败自动重试的状况,但有时又须要在发生某些错误的时候重试,好比超时,好比响应频繁被拒绝等等,在看过官方的示例后,本身写了一个自动重试的控制器。分享代码,供你们参考。java
下面是获取控制器的方法:编程
/** * 获取重试控制器 * * @return */ private static HttpRequestRetryHandler getHttpRequestRetryHandler() { return new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { logger.warn("请求发生错误!", exception); if (executionCount > HttpClientConstant.TRY_TIMES) return false; if (exception instanceof NoHttpResponseException) { logger.warn("没有响应异常"); sleep(1); return true; } else if (exception instanceof ConnectTimeoutException) { logger.warn("链接超时,重试"); sleep(5); return true; } else if (exception instanceof SSLHandshakeException) { logger.warn("本地证书异常"); return false; } else if (exception instanceof InterruptedIOException) { logger.warn("IO中断异常"); sleep(1); return true; } else if (exception instanceof UnknownHostException) { logger.warn("找不到服务器异常"); return false; } else if (exception instanceof SSLException) { logger.warn("SSL异常"); return false; } else if (exception instanceof HttpHostConnectException) { logger.warn("主机链接异常"); return false; } else if (exception instanceof SocketException) { logger.warn("socket异常"); return false; } else { logger.warn("未记录的请求异常:{}", exception.getClass()); } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 若是请求是幂等的,则重试 if (!(request instanceof HttpEntityEnclosingRequest)) { sleep(2); return true; } return false; } }; }
这样超时时间和重试次数来做为判断接口请求失败的依据了。下面是控制器设置方法:服务器
/** * 经过链接池获取https协议请求对象 * <p> * 增长默认的请求控制器,和请求配置,链接控制器,取消了cookiestore,单独解析响应set-cookie和发送请求的header,适配多用户同时在线的状况 * </p> * * @return */ private static CloseableHttpClient getCloseableHttpsClients() { // 建立自定义的httpsclient对象 CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).setRetryHandler(httpRequestRetryHandler).setDefaultRequestConfig(requestConfig).build(); // CloseableHttpClient client = HttpClients.createDefault();//非链接池建立 return client; }