【发布时间】:2019-04-05 18:33:06
【问题描述】:
所以我正在关注 retryHandler() 的这个例子,它有 try/finally。我的问题是:如何重试异常?
public class HttpClientRetryHandlerExample {
public static void main(String... args) throws IOException {
CloseableHttpClient httpclient = HttpClients.custom()
.setRetryHandler(retryHandler())
.build();
try {
HttpGet httpget = new HttpGet("http://localhost:1234");
System.out.println("Executing request " + httpget.getRequestLine());
httpclient.execute(httpget);
System.out.println("----------------------------------------");
System.out.println("Request finished");
} finally {
httpclient.close();
}
}
private static HttpRequestRetryHandler retryHandler(){
return (exception, executionCount, context) -> {
System.out.println("try request: " + executionCount);
if (executionCount >= 5) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
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;
};
}
}
问题是,为什么这个例子只有 try/finally 没有 catch ?这是否意味着所有异常都会转到 retryHandler() ?
【问题讨论】:
标签: java apache-httpclient-4.x closeablehttpresponse