HttpClient异步请求资源
package demo; import java.util.concurrent.CountDownLatch; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.nio.client.DefaultHttpAsyncClient; import org.apache.http.nio.client.HttpAsyncClient; import org.apache.http.nio.concurrent.FutureCallback; import org.apache.http.nio.reactor.IOReactorException; public class Main { /** * @param args * @throws IOReactorException * @throws InterruptedException */ public static void main(String[] args) throws IOReactorException, InterruptedException { final HttpAsyncClient httpclient = new DefaultHttpAsyncClient(); httpclient.start(); HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"), new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") }; final CountDownLatch latch = new CountDownLatch(requests.length); try { for (final HttpGet request: requests) { httpclient.execute(request, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + response.getStatusLine()); } public void failed(final Exception ex) { latch.countDown(); ex.printStackTrace(); } public void cancelled() { latch.countDown(); } }); } System.out.println("Doing..."); }finally { latch.await(); httpclient.shutdown(); } System.out.println("Done"); } }
相关推荐
Kafka 2020-09-18
Wepe0 2020-10-30
杜倩 2020-10-29
windle 2020-10-29
minerd 2020-10-28
mengzuchao 2020-10-22
Junzizhiai 2020-10-10
bxqybxqy 2020-09-30
风之沙城 2020-09-24
kingszelda 2020-09-22
大唐帝国前营 2020-08-18
yixu0 2020-08-17
TangCuYu 2020-08-15
xiaoboliu00 2020-08-15
songshijiazuaa 2020-08-15
xclxcl 2020-08-03
zmzmmf 2020-08-03
newfarhui 2020-08-03
likesyour 2020-08-01