Directly on the code
PackageOrg.jivesoftware.spark.util;importJava.io.ioexception;importJava.util.concurrent.countdownlatch;importJava.util.concurrent.executorservice;importJava.util.concurrent.executors;importOrg.apache.http.httpresponse;importOrg.apache.http.client.config.requestconfig;importOrg.apache.http.client.methods.httpget;importOrg.apache.http.concurrent.futurecallback;importOrg.apache.http.impl.nio.client.closeablehttpasyncclient;importOrg.apache.http.impl.nio.client.httpasyncclients;importOrg.jivesoftware.debugprint;importorg.jivesoftware.spark.sparkmanager;//asynchronous buried point data acquisition tool class public classHotclickasync {static Executorservice service = Executors.newsinglethreadexecutor ();//single thread//call HTTP request. does not block the main thread public static void SendRequest (finalString event) throwsInterruptedexception, IOException {Runnable run = newRunnable () {@Override public voidRun () {try{Sendrequestasync (Event,sparkmanager.getsessionmanager (). GetUserName ());} Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); } } }; Service.execute (run); }//block HTTP call private static voidSendrequestasync (String event,string username) throwsInterruptedexception, IOException {requestconfig requestconfig =Requestconfig.custom (). SetSocketTimeout (+)//HTTP timeout. Setconnecttimeout (+). Build (); Connection Timeout Closeablehttpasyncclient httpclient =Httpasyncclients.custom (). Setdefaultrequestconfig (Requestconfig). build (); Try{Httpclient.start (); final httpget[] requests = new httpget[] {newHttpGet ("http://XXXXXX.cn:81/HotClick.aspx?event=" + Event + "&username=" +username)//First acquisition address//, New HttpGet (" Http://mta.qq.com ")//second acquisition address, http://mta.qq.com/ }; Synchronization Count Final Countdownlatch latch = new countdownlatch (requests.length); for (final HttpGet request:requests) { Httpclient.execute (Request, New futurecallback() {@Override public void completed (final HttpResponse response) {Latch.countdown (); Debugprint.outstirng (Request.getrequestline () + "####->" + Response.getstatusline ()), @Override public void Failed (final Exception ex) {Latch.countdown (); Debugprint.outstirng (Request.getrequestline () + "####->" + ex), @Override public void cancelled () {latch.co Untdown (); Debugprint.outstirng (Request.getrequestline ()//+ "cancelled"); } }); } latch.await (); } finally {Httpclient.close ();} Debugprint.outstirng ("# # # Hotclickasync Done # # #");}}
Java example of asynchronous execution of multiple HTTP requests (requires Apache HTTP class library)