欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现HttpClient异步请求资源的方法

程序员文章站 2024-03-04 17:50:00
本文实例讲述了java实现httpclient异步请求资源的方法。分享给大家供大家参考。具体实现方法如下: package demo; import java....

本文实例讲述了java实现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");
 }
}

希望本文所述对大家的java程序设计有所帮助。