packagecom.inspur.demo.http.client;importjava.io.File;importjava.io.IOException;importjava.nio.CharBuffer;importjava.util.ArrayList;importjava.util.List;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.Future;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.NameValuePair;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.concurrent.FutureCallback;importorg.apache.http.entity.ContentType;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.nio.client.CloseableHttpAsyncClient;importorg.apache.http.impl.nio.client.HttpAsyncClients;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.nio.IOControl;importorg.apache.http.nio.client.methods.AsyncCharConsumer;importorg.apache.http.nio.client.methods.HttpAsyncMethods;importorg.apache.http.nio.client.methods.ZeroCopyConsumer;importorg.apache.http.nio.client.methods.ZeroCopyPost;importorg.apache.http.nio.protocol.HttpAsyncRequestProducer;importorg.apache.http.protocol.HttpContext;importorg.apache.http.util.EntityUtils;/*** 通过HttpClient调用Http接口*/
public classHttpAsyncClientCase {/*** GET请求*/
public static voidget() {
String requestPath= "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白";
CloseableHttpAsyncClient httpClient=HttpAsyncClients.createDefault();try{
httpClient.start();
HttpGet get= newHttpGet(requestPath);
Future future = httpClient.execute(get, null);
HttpResponse response=future.get();
System.out.println("GET返回状态:" +response.getStatusLine());
HttpEntity responseEntity=response.getEntity();
System.out.println("GET返回结果:" +EntityUtils.toString(responseEntity));//回调方式调用
final CountDownLatch latch = new CountDownLatch(1);final HttpGet get2 = newHttpGet(requestPath);
httpClient.execute(get2,new FutureCallback() {public void completed(finalHttpResponse response) {
latch.countDown();
System.out.println("GET(回调方式)返回状态:" +response.getStatusLine());try{
System.out.println("GET(回调方式)返回结果:" +EntityUtils.toString(response.getEntity()));
}catch(Exception e) {
e.printStackTrace();
}
}public void failed(finalException e) {
latch.countDown();
e.printStackTrace();
}public voidcancelled() {
latch.countDown();
System.out.println("cancelled");
}
});
latch.await();//流方式调用
final CountDownLatch latch2 = new CountDownLatch(1);final HttpGet get3 = newHttpGet(requestPath);
HttpAsyncRequestProducer producer3=HttpAsyncMethods.create(get3);
AsyncCharConsumer consumer3 = new AsyncCharConsumer() {
HttpResponse response;
@Overrideprotected void onResponseReceived(finalHttpResponse response) {this.response =response;
}
@Overrideprotected voidreleaseResources() {
}
@Overrideprotected HttpResponse buildResult(finalHttpContext context) {return this.response;
}
@Overrideprotected void onCharReceived(CharBuffer buf, IOControl ioctrl) throwsIOException {
System.out.println("GET(流方式)返回结果:" +buf.toString());
}
};
httpClient.execute(producer3, consumer3,new FutureCallback() {public void completed(finalHttpResponse response) {
latch2.countDown();
System.out.println("GET(流方式)返回状态:" +response.getStatusLine());
}public void failed(finalException e) {
latch2.countDown();
e.printStackTrace();
}public voidcancelled() {
latch2.countDown();
System.out.println("cancelled");
}
});
latch2.await();
}catch(Exception e) {
e.printStackTrace();
}finally{
close(httpClient);
}
}/*** POST请求(发送键值对数据)*/
public static voidpost() {
CloseableHttpAsyncClient httpClient=HttpAsyncClients.createDefault();try{
httpClient.start();
String requestPath= "http://localhost:8080/demo/httptest/getUser";
HttpPost post= newHttpPost(requestPath);
List list = new ArrayList();
list.add(new BasicNameValuePair("userId", "1000"));
list.add(new BasicNameValuePair("userName", "李白"));
post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
Future future = httpClient.execute(post, null);
HttpResponse response=future.get();
System.out.println("POST返回状态:" +response.getStatusLine());
HttpEntity responseEntity=response.getEntity();
System.out.println("POST返回结果:" +EntityUtils.toString(responseEntity));//回调方式和流方式调用类似
} catch(Exception e) {
e.printStackTrace();
}finally{
close(httpClient);
}
}/*** POST请求(发送json数据)*/
public static voidpost2() {
CloseableHttpAsyncClient httpClient=HttpAsyncClients.createDefault();try{
httpClient.start();
String requestPath= "http://localhost:8080/demo/httptest/addUser";
HttpPost post= newHttpPost(requestPath);
post.setHeader("Content-type", "application/json");
String param= "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
post.setEntity(new StringEntity(param, "utf-8"));
Future future = httpClient.execute(post, null);
HttpResponse response=future.get();
System.out.println("POST json返回状态:" +response.getStatusLine());
HttpEntity responseEntity=response.getEntity();
System.out.println("POST josn返回结果:" +EntityUtils.toString(responseEntity));//回调方式和流方式调用类似
} catch(Exception e) {
e.printStackTrace();
}finally{
close(httpClient);
}
}/*** 上传文件*/
public static voidupload() {
CloseableHttpAsyncClient httpClient=HttpAsyncClients.createDefault();try{
httpClient.start();
String requestPath= "http://localhost:8080/demo/httptest/upload";
ZeroCopyPost producer= new ZeroCopyPost(requestPath, new File("d:/a.jpg"), ContentType.create("text/plain"));
AsyncCharConsumer consumer = new AsyncCharConsumer() {
HttpResponse response;
@Overrideprotected void onResponseReceived(finalHttpResponse response) {this.response =response;
}
@Overrideprotected voidreleaseResources() {
}
@Overrideprotected HttpResponse buildResult(finalHttpContext context) {return this.response;
}
@Overrideprotected void onCharReceived(CharBuffer buf, IOControl ioctrl) throwsIOException {
System.out.println("upload返回结果:" +buf.toString());
}
};
Future future = httpClient.execute(producer, consumer, null);
HttpResponse response=future.get();
System.out.println("upload返回状态:" +response.getStatusLine());
}catch(Exception e) {
e.printStackTrace();
}finally{
close(httpClient);
}
}/*** 下载文件*/
public static voiddownload() {
CloseableHttpAsyncClient httpClient=HttpAsyncClients.createDefault();try{
httpClient.start();
String requestPath= "http://localhost:8080/demo/httptest/download";
HttpGet get= newHttpGet(requestPath);
HttpAsyncRequestProducer producer=HttpAsyncMethods.create(get);
File download= new File("d:/temp/download_" + System.currentTimeMillis() + ".jpg");
ZeroCopyConsumer consumer = new ZeroCopyConsumer(download) {
@Overrideprotected File process(final HttpResponse response, final File file, final ContentType contentType) throwsException {if (response.getStatusLine().getStatusCode() !=HttpStatus.SC_OK) {throw new ClientProtocolException("Upload failed: " +response.getStatusLine());
}returnfile;
}
};
Future future = httpClient.execute(producer, consumer, null);
System.out.println("download文件大小:" +future.get().length());
}catch(Exception e) {
e.printStackTrace();
}finally{
close(httpClient);
}
}private static voidclose(CloseableHttpAsyncClient httpClient) {try{if (httpClient != null) {
httpClient.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}public static voidmain(String[] args) {
get();
post();
post2();
upload();
download();
}
}