java实现HttpClient异步请求资源的方法
本文实例讲述了java实现HttpClient异步请求资源的方法。分享给大家供大家参考。具体实现方法如下:
packagedemo; importjava.util.concurrent.CountDownLatch; importorg.apache.http.HttpResponse; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.impl.nio.client.DefaultHttpAsyncClient; importorg.apache.http.nio.client.HttpAsyncClient; importorg.apache.http.nio.concurrent.FutureCallback; importorg.apache.http.nio.reactor.IOReactorException; publicclassMain{ /** *@paramargs *@throwsIOReactorException *@throwsInterruptedException */ publicstaticvoidmain(String[]args)throwsIOReactorException,InterruptedException{ finalHttpAsyncClienthttpclient=newDefaultHttpAsyncClient(); httpclient.start(); HttpGet[]requests=newHttpGet[]{ newHttpGet("http://www.apache.org/"), newHttpGet("https://www.verisign.com/"), newHttpGet("http://www.google.com/") }; finalCountDownLatchlatch=newCountDownLatch(requests.length); try{ for(finalHttpGetrequest:requests){ httpclient.execute(request,newFutureCallback<HttpResponse>(){ publicvoidcompleted(finalHttpResponseresponse){ latch.countDown(); System.out.println(request.getRequestLine()+"->"+response.getStatusLine()); } publicvoidfailed(finalExceptionex){ latch.countDown(); ex.printStackTrace(); } publicvoidcancelled(){ latch.countDown(); } }); } System.out.println("Doing..."); }finally{ latch.await(); httpclient.shutdown(); } System.out.println("Done"); } }
希望本文所述对大家的java程序设计有所帮助。