HttpClient can throw two types of exceptions: java.io.IOException in case of an I/O failure such as socket timeout or an socket reset and HttpException that signals an HTTP failure such as a violation of the HTTP protocol. Usually I/O errors are considered non-fatal and recoverable, whereas HTTP protocol errors are considered fatal and cannot be automatically recovered from.

HTTP transport safety

It is important to understand that the HTTP protocol is not well suited to all types of applications. HTTP is a simple request/response oriented protocol which was initially designed to support static or dynamically generated content retrieval. It has never been intended to support transactional operations. For instance, the HTTP server will consider its part of the contract fulfilled if it succeeds in receiving and processing the request, generating a response and sending a status code back to the client. The server will make no attempt to roll back the transaction if the client fails to receive the response in its entirety due to a read timeout, a request cancellation or a system crash. If the client decides to retry the same request, the server will inevitably end up executing the same transaction more than once. In some cases this may lead to application data corruption or inconsistent application state.

Even though HTTP has never been designed to support transactional processing, it can still be used as a transport protocol for mission critical applications provided certain conditions are met. To ensure HTTP transport layer safety the system must ensure the idempotency of HTTP methods on the application layer.

Idempotent methods

HTTP/1.1 specification defines an idempotent method as

[Methods can also have the property of "idempotence" in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request]

In other words the application ought to ensure that it is prepared to deal with the implications of multiple execution of the same method. This can be achieved, for instance, by providing a unique transaction id and by other means of avoiding execution of the same logical operation.

Please note that this problem is not specific to HttpClient. Browser based applications are subject to exactly the same issues related to HTTP methods non-idempotency.

HttpClient assumes non-entity enclosing methods such as GET and HEAD to be idempotent and entity enclosing methods such as POST and PUT to be not.

Automatic exception recovery

By default HttpClient attempts to automatically recover from I/O exceptions. The default auto-recovery mechanism is limited to just a few exceptions that are known to be safe.

  • HttpClient will make no attempt to recover from any logical or HTTP protocol errors (those derived from HttpException class).

  • HttpClient will automatically retry those methods that are assumed to be idempotent.

  • HttpClient will automatically retry those methods that fail with a transport exception while the HTTP request is still being transmitted to the target server (i.e. the request has not been fully transmitted to the server).

Request retry handler

In order to enable a custom exception recovery mechanism one should provide an implementation of the HttpRequestRetryHandler interface.

HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

    public boolean retryRequest(
IOException exception,
int executionCount,
HttpContext context) {
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 ConnectTimeoutException) {
// Connection refused
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;
} };
CloseableHttpClient httpclient = HttpClients.custom()
.setRetryHandler(myRetryHandler)
.build();

HttpClient(4.3.5) - Exception Handling的更多相关文章

  1. Exception Handling引入MVP

    异常处理(Exception Handling)是所有系统的最基本的基础操作之一,其它的比如日志(Logging).审核(Auditing).缓存(Caching).事务处理(Transaction) ...

  2. Unity、Exception Handling引入MVP

    什么是MVP?在“MVP初探”里就有讲过了,就是一种UI的架构模式. 简单的描述一下Unity和Exception Handling Application Block: Unity是一个轻量级的可扩 ...

  3. Exception Handling in ASP.NET Web API webapi异常处理

    原文:http://www.asp.net/web-api/overview/error-handling/exception-handling This article describes erro ...

  4. CoreCLR on Mac:体验managed exception handling

    C#测试代码: using System; class Program { static void A() { try { Console.WriteLine("Throwing an ex ...

  5. Exception Handling Statements (C# Reference)

    Exception Handling Statements (C# Reference) C# provides built-in support for handling anomalous sit ...

  6. Exception Handling in ASP.NET Web API

    public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErr ...

  7. [转]java-Three Rules for Effective Exception Handling

    主要讲java中处理异常的三个原则: 原文链接:https://today.java.net/pub/a/today/2003/12/04/exceptions.html Exceptions in ...

  8. How a C++ compiler implements exception handling

    Introduction One of the revolutionary features of C++ over traditional languages is its support for ...

  9. 黄聪:Microsoft Enterprise Library 5.0 系列教程(七) Exception Handling Application Block

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(七) Exception Handling Application Block 使用企业库异常处理应用程序模块的 ...

随机推荐

  1. UVA 11354 Bond(MST + LCA)

    n<=50000, m<=100000的无向图,对于Q<=50000个询问,每次求q->p的瓶颈路. 其实求瓶颈路数组maxcost[u][v]有用邻接矩阵prim的方法.但是 ...

  2. flex 弹性合模型

    网页布局(layout)是CSS的一个重点应用. 布局的传统解决方案,基于盒状模型,依赖 display属性 + position属性 + float属性.它对于那些特殊布局非常不方便,比如,垂直居中 ...

  3. python的sys.path

    python检测不到模块: No module named 是因为模块没有在sys.path中,查看sys.path的方法 import sys sys.path 发现确实没有加载到模块. windo ...

  4. Linq to SQL 绑定 ComboBox

    最近学习Linq to SQL,发现Linq是一个开发轻量数据库的好东西,大大简化了数据连接.查询过程.但是在绑定ComBoBox的时间发现了一个问题:Linq查询后得到的数据tolist后,只能实现 ...

  5. 如何彻底隐藏iOS7应用的status bar

    用xcode5开发新的iOS游戏,发现一个坑爹的现象,虽然我已经在info.plist里面把Status bar is initially hidden设置成了YES,但在设备上一跑还是看到丑陋的st ...

  6. Oracle 的 INSERT ALL和INSERT FIRST

    描述性的东西就不来了,搞技术的,最喜欢实在的实例.通过下面的例子,大家很快就能明白insert all 与 insert first 的功能,比文字描述更通俗易懂. 一.INSERT ALL 不带条件 ...

  7. win7常用快捷键

    Win+1:打开/显示超级任务栏第一个图标代表的程序Win+2:打开/显示超级任务栏第二个图标代表的程序(3.4.……如此类推)Win+Tab:3D切换窗口,你要是按住不松口,则所有窗口会轮流翻转Wi ...

  8. android-betterpickers

    https://github.com/derekbrameyer/android-betterpickers

  9. [Angular 2] Understanding OpaqueToken

    When using provider string tokens, there’s a chance they collide with other third-party tokens. Angu ...

  10. #define使用方法

    1.简单的define定义 #define MAXTIME 1000 一个简单的MAXTIME就定义好了,它代表1000,假设在程序里面写 if(i<MAXTIME){.........} 编译 ...