HttpClient(4.3.5) - Exception Handling
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
HttpExceptionclass).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的更多相关文章
- Exception Handling引入MVP
		
异常处理(Exception Handling)是所有系统的最基本的基础操作之一,其它的比如日志(Logging).审核(Auditing).缓存(Caching).事务处理(Transaction) ...
 - Unity、Exception Handling引入MVP
		
什么是MVP?在“MVP初探”里就有讲过了,就是一种UI的架构模式. 简单的描述一下Unity和Exception Handling Application Block: Unity是一个轻量级的可扩 ...
 - Exception Handling in ASP.NET Web API webapi异常处理
		
原文:http://www.asp.net/web-api/overview/error-handling/exception-handling This article describes erro ...
 - CoreCLR on Mac:体验managed exception handling
		
C#测试代码: using System; class Program { static void A() { try { Console.WriteLine("Throwing an ex ...
 - Exception Handling Statements (C# Reference)
		
Exception Handling Statements (C# Reference) C# provides built-in support for handling anomalous sit ...
 - Exception Handling in ASP.NET Web API
		
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErr ...
 - [转]java-Three Rules for Effective Exception Handling
		
主要讲java中处理异常的三个原则: 原文链接:https://today.java.net/pub/a/today/2003/12/04/exceptions.html Exceptions in ...
 - How a C++ compiler implements exception handling
		
Introduction One of the revolutionary features of C++ over traditional languages is its support for ...
 - 黄聪:Microsoft Enterprise Library 5.0 系列教程(七) Exception Handling Application Block
		
原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(七) Exception Handling Application Block 使用企业库异常处理应用程序模块的 ...
 
随机推荐
- javascript表单(form)序列化
			
function serialize(form){ var part =[]; var field = null; var i; var j; var len; var optLen; var opt ...
 - C# 中的sealed修饰符学习
			
转载原地址 http://developer.51cto.com/art/200908/147327.htm C#语言还是比较常见的东西,这里我们主要介绍C# sealed修饰符,包括介绍两个修饰符在 ...
 - HDU 4462 Scaring the Birds (暴力求解,二进制法)
			
题意:给定一个 n*n的矩阵,在一些位置放上稻草人,每个稻草人的范围是一定,问你最少几个能覆盖整个矩阵. 析:稻草人最多才10个,所以考虑暴力,然后利用二进制法,很容易求解,并且时间很少0ms,注意有 ...
 - 多线程和Boost::Asio
			
线程安全 一般的,高并发使用不同的对象是安全的,在高并发中使用单一的对象是不安全的,io_service类型提供了单对象高并发的强安全保证. 线程池 多线程可能调用io_service::run()来 ...
 - C#文件后缀名详解
			
C#文件后缀名详解 .sln:解决方案文件,为解决方案资源管理器提供显示管理文件的图形接口所需的信息. .csproj:项目文件,创建应用程序所需的引用.数据连接.文件夹和文件的信息. .aspx:W ...
 - java 分页
			
ListAction.java package com.sy.action; import java.util.List; import com.opensymphony.xwork2.ActionS ...
 - ALV的报表对用户定义格式的控制(ALV  I_SAVE)
			
很多ALV的报表都需要手动的进行设置格式以使数据看上去更有意义和条理,如果每次进来都重新操作一遍是很烦人的,所以SAP有提供了一个保存格式的功能,保存格式可以是 '缺省设置' 和 '特定用户' 两种 ...
 - Educational Codeforces Round 2 C. Make Palindrome 贪心
			
C. Make Palindrome Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/600/pr ...
 - web app页面要求
			
代码: <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum- ...
 - 【javaSE】HashSet和HashMap
			
************************************************************************ ****原文:blog.csdn.net/clar ...