Java调用Http接口(5)--HttpAsyncClient调用Http…

2019-11-27 16:06:01来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Java调用Http接口(5)--HttpAsyncClient调用Http接口

HttpAsyncClient是HttpClient的异步版本,提供异步调用的api。文中所使用到的软件版本:Java 1.8.0_191、HttpClient 4.1.4。

1、服务端

参见Java调用Http接口(1)--编写服务端 

2、调用

2.1、GET请求

    public static void get() {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        try {
            httpClient.start();
            String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8");
            HttpGet get = new HttpGet(requestPath);
            Future<HttpResponse> 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 = new HttpGet(requestPath);
            httpClient.execute(get2, new FutureCallback<HttpResponse>() {
                public void completed(final HttpResponse 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(final Exception e) {
                    latch.countDown();
                    e.printStackTrace();
                }
                public void cancelled() {
                    latch.countDown();
                    System.out.println("cancelled");
                }

            });
            latch.await();
            
            //流方式调用
            final CountDownLatch latch2 = new CountDownLatch(1);
            final HttpGet get3 = new HttpGet(requestPath);
            HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(get3);
            AsyncByteConsumer<HttpResponse> consumer3 = new AsyncByteConsumer<HttpResponse>() {
                HttpResponse response;
                @Override
                protected void onResponseReceived(final HttpResponse response) {
                    this.response = response;
                }
                @Override
                protected void releaseResources() {
                }
                @Override
                protected HttpResponse buildResult(final HttpContext context) {
                    return this.response;
                }
                @Override
                protected void onByteReceived(ByteBuffer buf, IOControl ioctrl) throws IOException {
                    System.out.println("GET(流方式)返回结果:" + new String(buf.array()));
                }
            };
            httpClient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() {
                public void completed(final HttpResponse response) {
                    latch2.countDown();
                    System.out.println("GET(流方式)返回状态:" + response.getStatusLine());
                }
                public void failed(final Exception e) {
                    latch2.countDown();
                    e.printStackTrace();
                }
                public void cancelled() {
                    latch2.countDown();
                    System.out.println("cancelled");
                }
            });
            latch2.await();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
    }

2.2、POST请求(发送键值对数据)

    public static void post() {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        try {
            httpClient.start();
            String requestPath = "http://localhost:8080/demo/httptest/getUser";
            HttpPost post = new HttpPost(requestPath);
            
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("userId", "1000"));
            list.add(new BasicNameValuePair("userName", "李白"));
            post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
            
            Future<HttpResponse> 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 {
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
    }

2.3、POST请求(发送JSON数据)

    public static void post2() {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        try {
            httpClient.start();
            String requestPath = "http://localhost:8080/demo/httptest/addUser";
            HttpPost post = new HttpPost(requestPath);
            post.setHeader("Content-type", "application/json");
            String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
            post.setEntity(new StringEntity(param, "utf-8"));
            
            Future<HttpResponse> 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 {
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
    }

2.4、上传文件

    public static void upload() {
        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"));
            AsyncByteConsumer<HttpResponse> consumer = new AsyncByteConsumer<HttpResponse>() {
                HttpResponse response;
                @Override
                protected void onResponseReceived(final HttpResponse response) {
                    this.response = response;
                }
                @Override
                protected void releaseResources() {
                }
                @Override
                protected HttpResponse buildResult(final HttpContext context) {
                    return this.response;
                }
                @Override
                protected void onByteReceived(ByteBuffer buf, IOControl ioctrl) throws IOException {
                    System.out.println("upload返回结果:" + new String(buf.array()));
                }
            };
            Future<HttpResponse> future = httpClient.execute(producer, consumer, null);
            HttpResponse response = future.get();
            System.out.println("upload返回状态:" + response.getStatusLine());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
    }

2.5、下载文件

    public static void download() {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        try {
            httpClient.start();
            String requestPath = "http://localhost:8080/demo/httptest/download";
            HttpGet get = new HttpGet(requestPath);
            HttpAsyncRequestProducer producer = HttpAsyncMethods.create(get);
            File download = new File("d:/temp/download_" + System.currentTimeMillis() + ".jpg");
            ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) {
                @Override
                protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception {
                    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                        throw new ClientProtocolException("Upload failed: " + response.getStatusLine());
                    }
                    return file;
                }
            };
            Future<File> future = httpClient.execute(producer, consumer, null);
            System.out.println("download文件大小:" + future.get().length());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
    }

2.6、完整例子

package com.inspur.demo.http.client;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.AsyncByteConsumer;
import org.apache.http.nio.client.methods.HttpAsyncMethods;
import org.apache.http.nio.client.methods.ZeroCopyConsumer;
import org.apache.http.nio.client.methods.ZeroCopyPost;
import org.apache.http.nio.protocol.HttpAsyncRequestProducer;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * 通过HttpClient调用Http接口
 *
 */
public class HttpAsyncClientCase {
    /**
     *  GET请求
     */
    public static void get() {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        try {
            httpClient.start();
            String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8");
            HttpGet get = new HttpGet(requestPath);
            Future<HttpResponse> 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 = new HttpGet(requestPath);
            httpClient.execute(get2, new FutureCallback<HttpResponse>() {
                public void completed(final HttpResponse 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(final Exception e) {
                    latch.countDown();
                    e.printStackTrace();
                }
                public void cancelled() {
                    latch.countDown();
                    System.out.println("cancelled");
                }

            });
            latch.await();
            
            //流方式调用
            final CountDownLatch latch2 = new CountDownLatch(1);
            final HttpGet get3 = new HttpGet(requestPath);
            HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(get3);
            AsyncByteConsumer<HttpResponse> consumer3 = new AsyncByteConsumer<HttpResponse>() {
                HttpResponse response;
                @Override
                protected void onResponseReceived(final HttpResponse response) {
                    this.response = response;
                }
                @Override
                protected void releaseResources() {
                }
                @Override
                protected HttpResponse buildResult(final HttpContext context) {
                    return this.response;
                }
                @Override
                protected void onByteReceived(ByteBuffer buf, IOControl ioctrl) throws IOException {
                    System.out.println("GET(流方式)返回结果:" + new String(buf.array()));
                }
            };
            httpClient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() {
                public void completed(final HttpResponse response) {
                    latch2.countDown();
                    System.out.println("GET(流方式)返回状态:" + response.getStatusLine());
                }
                public void failed(final Exception e) {
                    latch2.countDown();
                    e.printStackTrace();
                }
                public void cancelled() {
                    latch2.countDown();
                    System.out.println("cancelled");
                }
            });
            latch2.await();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
    }
    
    /**
     *  POST请求(发送键值对数据)
     */
    public static void post() {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        try {
            httpClient.start();
            String requestPath = "http://localhost:8080/demo/httptest/getUser";
            HttpPost post = new HttpPost(requestPath);
            
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("userId", "1000"));
            list.add(new BasicNameValuePair("userName", "李白"));
            post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
            
            Future<HttpResponse> 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 {
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
    }
    
    /**
     *  POST请求(发送json数据)
     */
    public static void post2() {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        try {
            httpClient.start();
            String requestPath = "http://localhost:8080/demo/httptest/addUser";
            HttpPost post = new HttpPost(requestPath);
            post.setHeader("Content-type", "application/json");
            String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
            post.setEntity(new StringEntity(param, "utf-8"));
            
            Future<HttpResponse> 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 {
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
    }
    
    /**
     * 上传文件
     */
    public static void upload() {
        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"));
            AsyncByteConsumer<HttpResponse> consumer = new AsyncByteConsumer<HttpResponse>() {
                HttpResponse response;
                @Override
                protected void onResponseReceived(final HttpResponse response) {
                    this.response = response;
                }
                @Override
                protected void releaseResources() {
                }
                @Override
                protected HttpResponse buildResult(final HttpContext context) {
                    return this.response;
                }
                @Override
                protected void onByteReceived(ByteBuffer buf, IOControl ioctrl) throws IOException {
                    System.out.println("upload返回结果:" + new String(buf.array()));
                }
            };
            Future<HttpResponse> future = httpClient.execute(producer, consumer, null);
            HttpResponse response = future.get();
            System.out.println("upload返回状态:" + response.getStatusLine());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
    }
    
    /**
     * 下载文件
     */
    public static void download() {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        try {
            httpClient.start();
            String requestPath = "http://localhost:8080/demo/httptest/download";
            HttpGet get = new HttpGet(requestPath);
            HttpAsyncRequestProducer producer = HttpAsyncMethods.create(get);
            File download = new File("d:/temp/download_" + System.currentTimeMillis() + ".jpg");
            ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) {
                @Override
                protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception {
                    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                        throw new ClientProtocolException("Upload failed: " + response.getStatusLine());
                    }
                    return file;
                }
            };
            Future<File> future = httpClient.execute(producer, consumer, null);
            System.out.println("download文件大小:" + future.get().length());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
    }
    
    public static void main(String[] args) {
        get();
        post();
        post2();
        upload();
        download();
    }
}
View Code

 

 


原文链接:https://www.cnblogs.com/wuyongyin/p/11940562.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Java 复习笔记8 - 多线程

下一篇:Python 深入浅出支持向量机(SVM)算法