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. poj 3501 Escape from Enemy Territory 二分+bfs

    水题,不解释. #include<stdio.h> #include<math.h> #include<cstring> #include<algorithm ...

  2. MEF 编程指南(一):在应用中托管 MEF

    在应用程序中托管(Hosing) MEF 涉及到创建组合容器(CompositionContainer) 实例,添加可组合部件(Composable Parts),包括应用程序宿主(Host)本身并进 ...

  3. 深度学习论文笔记-Deep Learning Face Representation from Predicting 10,000 Classes

    来自:CVPR 2014   作者:Yi Sun ,Xiaogang Wang,Xiaoao Tang 题目:Deep Learning Face Representation from Predic ...

  4. WIN8重见开始菜单

    从win7进入win8感觉不适应,做为一个程序开发人员,更觉得不爽,因此想着如何恢复开始菜单,查了很多文章终于找到方法 首先,在桌面版Windows 8启动资源管理器,单击工具栏上的“查看”选项卡后, ...

  5. System.exit()方法的作用

    查看java.lang.System的源码.我们能够看到System.exit()这种方法等价于Runtime.exit(),代码例如以下: /** * Terminates the currentl ...

  6. mysql用变量存储插入的id

    INSERT into a(value) values ('test');#set @last_id = LAST_INSERT_ID();set @last_id = (select max(id) ...

  7. 关于flash player debugger 无法弹窗报错的解决办法

    第一个是IE的插件, Download the Windows Flash Player 10.2 ActiveX control content debugger (for IE) (EXE, 2. ...

  8. UNIX标准化及实现之POSIX标准必需头文件

    POSIX标准定义的必需头文件 头文件 说明 <dirent.h> 目录项 <fcntl.h> 文件控制 <fnmatch.h> 文件名匹配类型 <glob. ...

  9. jQuery事件之on()方法绑定多个选择器,多个事件

    这样一个需求,如果用live()方法实现的话 非常简单,容易理解. $('nav li, #sb-nav li, #help li').live('click', function () { // c ...

  10. mysql索引需要了解的几个注意

    板子之前做过2年web开发培训(入门?),获得挺多学生好评,这是蛮有成就感的一件事,准备花点时间根据当时的一些备课内容整理出一系列文章出来,希望能给更多人带来帮助,这是系列文章的第一篇 注:科普文章一 ...