Using Apache HttpClient 4.x for exception retry

Source: Internet
Author: User
Tags httpcontext

When making an HTTP request, it is unavoidable to encounter a failure of the request, after the failure requires a re-request to try to get the data again.

Apache's HttpClient provides an exception-retry mechanism in which we can flexibly define which exceptions to retry.

Retry Prerequisites

The requested method must be idempotent: that is, multiple requests the server end result should be accurate and consistent.

Suitable method: For example, according to the ID, modify the name of the person, no matter how many times the request results are the same, this is idempotent. Unsuitable method: For example, reduce account number 50 yuan, multiple requests will be deducted several times. Implementation to implement an exception retry, you need to implement an interface that it providesHttprequestretryhandler, and implement the Retryrequest method. Then set into HttpClient. The httpclient has a retry mechanism. The httpclient itself providesStandardhttprequestretryhandler and Defaulthttprequestretryhandler two implementation classes. Defaulthttprequestretryhandler inherits from Defaulthttprequestretryhandler, Standardhttprequestretryhandler The default methods are idempotent, such as put, and other methods other than post, if the custom can refer to its implementation method. The code is as follows:
1 Importjava.io.IOException;2 Importjava.io.InterruptedIOException;3 Importjava.net.ConnectException;4 Importjava.net.UnknownHostException;5 6 Importjavax.net.ssl.SSLException;7 8 Importorg.apache.commons.lang3.ObjectUtils;9 Importorg.apache.commons.lang3.StringUtils;Ten Importorg.apache.http.Consts; One Importorg.apache.http.HttpEntityEnclosingRequest; A Importorg.apache.http.HttpRequest; - ImportOrg.apache.http.HttpStatus; - Importorg.apache.http.ParseException; the ImportOrg.apache.http.client.HttpRequestRetryHandler; - ImportOrg.apache.http.client.config.RequestConfig; - ImportOrg.apache.http.client.methods.CloseableHttpResponse; - ImportOrg.apache.http.client.methods.HttpPost; + ImportOrg.apache.http.client.protocol.HttpClientContext; - ImportOrg.apache.http.entity.ContentType; + Importorg.apache.http.entity.StringEntity; A Importorg.apache.http.impl.client.CloseableHttpClient; at Importorg.apache.http.impl.client.HttpClients; - ImportOrg.apache.http.protocol.HttpContext; - Importorg.apache.http.util.EntityUtils; -  - /** -  * @author* in * @date May 18, 2017 morning 9:17:30 -  * to * @Description +  */ -  Public classHttppostutils { the     /** *      *  $      * @paramURIPanax Notoginseng * The request address -      * @paramJSON the * The request data that must is a JSON string +      * @paramRetryCount A * The number of times this method has been unsuccessfully the * Executed +      * @paramConnectTimeout - * The timeout in milliseconds until a connection is established $      * @paramConnectionrequesttimeout $ * The timeout in milliseconds used when requesting a connection - * From the connection Manager -      * @paramSockettimeout the * The socket timeout in milliseconds, which are the timeout for - * Waiting for data or, put differently, a maximum periodWuyi * Inactivity between, consecutive data packets the      * @returnNULL when method parameter is null, "", "" -      * @throwsIOException Wu * If HTTP connection can not opened or closed successfully -      * @throwsparseexception About * If response data can not parsed successfully $      */ -      PublicString Retrypostjson (String uri, string json,intRetryCount,intConnectTimeout, -             intConnectionrequesttimeout,intSockettimeout)throwsIOException, ParseException { -         if(Stringutils.isanyblank (URI, JSON)) { A             return NULL; +         } the  -Httprequestretryhandler Httprequestretryhandler =NewHttprequestretryhandler () { $  the @Override the              Public BooleanRetryrequest (IOException exception,intExecutioncount, HttpContext context) { the                 if(Executioncount >RetryCount) { the                     //Do not retry if-over Max Retry Count -                     return false; in                 } the                 if(Exceptioninstanceofinterruptedioexception) { the                     //An input or output transfer have been terminated About                     return false; the                 } the                 if(Exceptioninstanceofunknownhostexception) { the                     //Unknown Host modify code to retry when the host is not recognized, the actual business should not be retried when not recognized, and again in order to demonstrate the retry process, execution will show the output below RetryCount times +SYSTEM.OUT.PRINTLN ("Host retry not recognized");return true; -                 } the                 if(Exceptioninstanceofconnectexception) {Bayi                     //Connection refused the                     return false; the                 } -                 if(Exceptioninstanceofsslexception) { -                     //SSL Handshake Exception the                     return false; the                 } theHttpclientcontext ClientContext =httpclientcontext.adapt (context); theHttpRequest request =clientcontext.getrequest (); -                 BooleanIdempotent =! (Requestinstanceofhttpentityenclosingrequest); the                 if(idempotent) { the                     //Retry If the request is considered idempotent the                     return true;94                 } the                 return false; the             } the         };98  AboutCloseablehttpclient client =Httpclients.custom (). Setretryhandler (Httprequestretryhandler). build (); -HttpPost post =NewHttpPost (URI);101         //Create Request Data102stringentity entity =Newstringentity (JSON, Contenttype.application_json);103         //Set Request Body104 post.setentity (entity); the 106Requestconfig config =Requestconfig.custom (). Setconnecttimeout (ConnectTimeout)107 . Setconnectionrequesttimeout (connectionrequesttimeout). SetSocketTimeout (Sockettimeout). build ();108 post.setconfig (config);109         //Response Content theString responsecontent =NULL;111Closeablehttpresponse response =NULL; the         Try {113Response =Client.execute (Post, Httpclientcontext.create ()); the             if(Response.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) { theResponsecontent =entityutils.tostring (Response.getentity (), Consts.UTF_8.name ()); the             }117}finally {118             if(Objectutils.anynotnull (response)) {119 response.close (); -             }121             if(objectutils.anynotnull (client)) {122 client.close ();123             }124         } the         returnresponsecontent;126}

Reprinted from: http://www.cnblogs.com/wuxiaofeng/p/6879292.html, thanks for sharing.

Using Apache HttpClient 4.x for exception retry

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.