If you've seen the example of a mock post request for easy play with httpclient, which I wrote some days ago, you can see that this article is a piece of cake, and if you know some nio by the way, there is basically no pressure. Because Httpasyncclient is more of a nio than httpclient, this is why it supports asynchrony.
But I have a question, although NIO is synchronous non-blocking IO, but Httpasyncclient provides a mechanism for callbacks, craved is similar to Netty, so you can simulate an aio-like effect. But the official online example is basically using future
Well, I did it in a callback way anyway. The code is basically consistent with httpclient. There are 2 places in a different place: different when you configure SSL, and callbacks when you invoke execute mode. The specific code is as follows:
Package Com.tgb.ccl.http.simpledemo;import Java.io.file;import Java.io.fileinputstream;import java.io.IOException; Import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.reader;import Java.security.keymanagementexception;import Java.security.keystore;import Java.security.keystoreexception;import Java.security.nosuchalgorithmexception;import Java.security.cert.certificateexception;import Java.util.ArrayList ; Import Java.util.hashmap;import Java.util.list;import java.util.map;import Java.util.map.entry;import Javax.net.ssl.sslcontext;import Javax.net.ssl.trustmanager;import Javax.net.ssl.x509trustmanager;import Org.apache.http.httpentity;import Org.apache.http.httphost;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.parseexception;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httppost;import Org.apache.http.concurrent.FuTurecallback;import Org.apache.http.config.registry;import Org.apache.http.config.registrybuilder;import Org.apache.http.conn.ssl.trustselfsignedstrategy;import Org.apache.http.impl.conn.DefaultProxyRoutePlanner; Import Org.apache.http.impl.nio.client.closeablehttpasyncclient;import Org.apache.http.impl.nio.client.httpasyncclientbuilder;import org.apache.http.impl.nio.client.HttpAsyncClients; Import Org.apache.http.impl.nio.conn.poolingnhttpclientconnectionmanager;import Org.apache.http.impl.nio.reactor.defaultconnectingioreactor;import Org.apache.http.impl.nio.reactor.ioreactorconfig;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.nio.conn.noopiosessionstrategy;import Org.apache.http.nio.conn.schemeiosessionstrategy;import Org.apache.http.nio.conn.ssl.ssliosessionstrategy;import Org.apache.http.nio.reactor.connectingioreactor;import Org.apache.http.ssl.sslcontexts;import org.apache.http.util.entityutils;/** * Httpasyncclient analog POST Request Simple example * * @ Author Arron * @daTE November 1, 2015 PM 2:23:18 * @version 1.0 */public class Simplehttpasyncclientdemo {/** * Set Trust Custom certificate * * @param KEYSTOREPA Th keystore Path * @param keystorepass keystore password * @return */public static Sslcontext custom (string Keystorepath, String keystorepass) { Sslcontext sc = null; FileInputStream instream = null; KeyStore Truststore = null;try {truststore = Keystore.getinstance (Keystore.getdefaulttype ()); instream = new FileInputStream (New File (Keystorepath)); Truststore.load (Instream, Keystorepass.tochararray ());// Trust your own CA and all self-signed certificates sc = Sslcontexts.custom (). Loadtrustmaterial (Truststore, New Trustselfsignedstrategy ()). build ();} catch (Keystoreexception | nosuchalgorithmexception| certificateexception | IOException | Keymanagementexception e) {e.printstacktrace ();} finally {try {instream.close ()} catch (IOException e) {}}return sc;} /** * Bypass Verification * * @return * @throws nosuchalgorithmexception * @throws keymanagementexception */public static Sslcontext C Reateignoreverifyssl () throws NoSuchAlgorithmException, keymanagementexception {Sslcontext sc = sslcontext.getinstance ("SSLv3");//implements a X509trustmanager interface for bypassing authentication, Do not modify the method inside X509trustmanager TrustManager = new X509trustmanager () {@Overridepublic void checkclienttrusted ( Java.security.cert.x509certificate[] paramarrayofx509certificate,string paramstring) throws CertificateException {} @Overridepublic void checkservertrusted (java.security.cert.x509certificate[] paramarrayofx509certificate,string paramstring) throws Certificateexception {} @Overridepublic java.security.cert.x509certificate[] Getacceptedissuers ( {return null;}}; Sc.init (NULL, new trustmanager[] {TrustManager}, NULL); return SC;} /** * Set Agent * @param builder * @param hostorip * @param port */public static Httpasyncclientbuilder proxy (String Hostorip, int port) {///In turn, proxy address, proxy port number, protocol type Httphost proxy = new Httphost (Hostorip, Port, "http"); Defaultproxyrouteplanner Routeplanner = new Defaultproxyrouteplanner (proxy); return Httpasyncclients.custom (). Setrouteplanner (Routeplanner);} /** * Mock Request * * @param URL Resource address * @param map parameter list * @param encoding code * @param handler Result Processing class * @return * @throws Nosuchalgorithmexcepti On * @throws keymanagementexception * @throws ioexception * @throws clientprotocolexception */public static void Send ( String URL, map<string,string> map,final string encoding, final Asynchandler handler) throws Keymanagementexception, NoSuchAlgorithmException, clientprotocolexception, IOException {//Bypass certificate validation, Handling HTTPS requests Sslcontext Sslcontext = Createignoreverifyssl (); Set protocol HTTP and HTTPS for the processing of socket-Link Factory objects registry<schemeiosessionstrategy> sessionstrategyregistry = Registrybuilder.<schemeiosessionstrategy>create (). Register ("http", Noopiosessionstrategy.instance) . Register ("https", new Ssliosessionstrategy (Sslcontext)). build ();//Configure IO thread Ioreactorco Nfig ioreactorconfig = Ioreactorconfig.custom (). Setiothreadcount (Runtime.getruntime (). AvailableProcessors ()). Build ();//Set Connection pool size CONNECTINGIOREACTor ioreactor;ioreactor = new Defaultconnectingioreactor (ioreactorconfig); Poolingnhttpclientconnectionmanager Connmanager = new Poolingnhttpclientconnectionmanager (IoReactor, NULL, Sessionstrategyregistry, NULL); Create a custom HttpClient object final Closeablehttpasyncclient client = proxy ("127.0.0.1", 8087). Setconnectionmanager ( Connmanager). Build ();//closeablehttpasyncclient client = Httpasyncclients.createdefault ();//Create Post method Request Object HttpPost HttpPost = new HttpPost (URL);//reload parameter list<namevaluepair> Nvps = new arraylist<namevaluepair> (); if (map!=null {for (entry<string, string> entry:map.entrySet ()) {Nvps.add (New Basicnamevaluepair (), Entry.getvalue ()));}} Set parameters to the Request object in Httppost.setentity (new Urlencodedformentity (Nvps, encoding)); SYSTEM.OUT.PRINTLN ("Request address:" +url); SYSTEM.OUT.PRINTLN ("Request parameter:" +nvps.tostring ());//Set header information//Specify Header "Content-type", "User-agent" Httppost.setheader (" Content-type "," application/x-www-form-urlencoded "); Httppost.setheader (" User-agent ", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; Digext);//Start the Clientclient.start ();//Perform the request operation and get the result (async) Client.execute (HttpPost, New futurecallback< Httpresponse> () {@Overridepublic void failed (Exception ex) {handler.failed (ex); close (client);} @Overridepublic Void completed (HttpResponse resp) {String body= "";//the Use of entityutils.tostring () method here will be a large probability error, cause: Not accepted complete, Link closed try {httpentity entity = resp.getentity (); if (entity! = null) {final InputStream instream = Entity.getcontent (); try {f inal StringBuilder sb = new StringBuilder (), final char[] tmp = new char[1024];final Reader reader = new InputStreamReader ( instream,encoding); int L;while ((l = reader.read (tmp))! =-1) {sb.append (tmp, 0, L);} BODY = Sb.tostring ();} finally {instream.close (); Entityutils.consume (entity);}}} catch (ParseException | IOException e) {e.printstacktrace ();} handler.completed (body); Close (client);} @Overridepublic void cancelled () {handler.cancelled (); Close (client);}}); /** * Close Client Object * * @param client */private STAtic void Close (closeablehttpasyncclient client) {try {client.close ();} catch (IOException e) {e.printstacktrace ()}} Static class Asynchandler implements ihandler{@Overridepublic Object failed (Exception e) {System.err.println ( Thread.CurrentThread (). GetName () + "--failed--" +e.getclass (). GetName () + "--" +e.getmessage ()); return null;} @Overridepublic Object completed (String respbody) {System.out.println (Thread.CurrentThread (). GetName () + "--Get content:" + respbody); return null;} @Overridepublic Object cancelled () {System.out.println (Thread.CurrentThread (). GetName () + "--canceled"); return null;}} /** * Callback Processing interface * * @author Arron * @date November 10, 2015 Morning 10:05:40 * @version 1.0 */public Interface Ihandler {/** * When handling exceptions, execute The method * @return */object failed (Exception e),/** * When handled normally, executes the method * @return */object completed (String respbody);/** * When processing cancellation, execute the Method * @return */object cancelled ();}}
to a test class:
public static void Main (string[] args) throws Keymanagementexception, NoSuchAlgorithmException, Clientprotocolexception, IOException {Asynchandler handler = new Asynchandler (); String url = "http://php.weather.sina.com.cn/iframe/index/w_cl.php"; map<string, string> map = new hashmap<string, string> (), Map.put ("code", "JS"), Map.put ("Day", "0"); Map.put ( "City", "Shanghai"), Map.put ("DFC", "1"), Map.put ("CharSet", "Utf-8"); Send (URL, map, "Utf-8", Handler); System.out.println ("-----------------------------------"); Map.put ("City", "Beijing"); Send (URL, map, "Utf-8", Handler); System.out.println ("-----------------------------------");}
The test results are as follows:
Very simple, actually based on the Httpasyncclient tool Class I have also encapsulated, similar to the HttpClient tool class. The code has been submitted to: Https://github.com/Arronlong/httpclientUtil. Interested in self-download, the blog will no longer share.
Example of a mock post request for easy httpasyncclient