需要用到的包(包版本应该可能不同):
httpcore-4.1.4.jar
httpsayncclient-4.0-alpha3.jar
httpcore-nio-4.2-alpha3.jar
/**
* 异步http请求
* @author Old Zhang
*
*/
public class AsyncClientHttpExchange {
public static void main(String[] args) throws Exception {
sendUrl();
}
public static void sendUrl() throws Exception {
String str="hello,world";
String url="https://www.baidu.com"+"?str:"+str;
//String response = getHttpResponse(url);
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
httpclient.start();
final CountDownLatch latch = new CountDownLatch(1);
final HttpGet request = new HttpGet("https://www.baidu.com");
System.out.println(" caller thread id is : " + Thread.currentThread().getId());
httpclient.execute(request, new FutureCallback<HttpResponse>() {
public void completed(final HttpResponse response) {
latch.countDown();
System.out.println(" callback thread id is : " + Thread.currentThread().getId());
System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
try {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(" response content is : " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
public void failed(final Exception ex) {
latch.countDown();
System.out.println(request.getRequestLine() + "->" + ex);
System.out.println(" callback thread id is : " + Thread.currentThread().getId());
}
public void cancelled() {
latch.countDown();
System.out.println(request.getRequestLine() + " cancelled");
System.out.println(" callback thread id is : " + Thread.currentThread().getId());
}
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
httpclient.close();
} catch (IOException ignore) {
}
}
}