Java中对于httpClient的异步请求处理

注意:使用这个前提要导入相对应的jar包,这里使用的是Apache的httpComponents;

直接在pom.xml文件里加入:


   org.apache.httpcomponents
   httpasyncclient
   4.1.1
对应的测试用例:使用的方法
@Test
public void post(){
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();
    final CountDownLatch latch = new CountDownLatch(1);
    final HttpPost post = new HttpPost(url);
    
    //设置请求头    这里根据个人来定义
     post.addHeader("Content-type", "application/json; charset=utf-8");
    post.setHeader("Accept", "application/json");

    //执行
    client.execute(post, new FutureCallback() {
        //执行异步操作  请求完成后
        public void completed(final HttpResponse response) {
            latch.countDown();
            //响应内容
            int a = response.getStatusLine().getStatusCode();
            System.out.println("状态码:"+a);
            if (a == 200) {
                System.out.println("成功!");
            } else {
                try {
                //输出响内容
                   System.out.println(response.getStatusLine().getStatusCode()
                            + "  " + EntityUtils.toString(response.getEntity(), "UTF-8"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //请求失败处理
        public void failed(final Exception ex) {
            latch.countDown();
        }

        //请求取消后处理
        public void cancelled() {
            latch.countDown();
        }

    });

    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //关闭
    try {
        client.close();
    } catch (IOException ignore) {

    }
}

这里很要注意的是在 实例化得到client对象后一定要记得调用client.start();方法,这里是和httpClient同步不一样的地方!!

 CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();

你可能感兴趣的:(工具)