Java通过httpClient同步异步发送请求

Posted 宣之于口

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java通过httpClient同步异步发送请求相关的知识,希望对你有一定的参考价值。

异步和同步

概念:
同步:发送一个请求,需要等待返回结果,然后才能发送下一个请求
异步:发送一个请求,不需要等待返回结果,随时可以发送下一个请求

Java 同步 GET 方法

 private void sendRequest() throws Exception
    String path ="/statistic/info";
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 创建一个 GET 请求
    HttpGet httpGet = new HttpGet(path);
    // 执行请求
    CloseableHttpResponse response =httpClient.execute(httpGet);
    //取响应的结果
    int statusCode =response.getStatusLine().getStatusCode();
    System.out.println(statusCode);
    String content = EntityUtils.toString(response.getEntity(), "UTF-8");
    System.out.println(content);
    //关闭httpclient
    response.close();
    httpClient.close();

Java Post方法

private void sendRequest() throws Exception
    String path ="http://localhost:8080/Baas/docs/index.html#!/device/payment.do";
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 创建一个 GET 请求
    HttpGet httpPost = new HttpGet(path);
    // 执行请求
    CloseableHttpResponse response =httpClient.execute(httpPost);
    //取响应的结果
    String content = EntityUtils.toString(response.getEntity(), "UTF-8");
    System.out.println(content);
    //关闭httpclient
    response.close();
    httpClient.close();

Java的异步HttpClient

1 . Maven 设置

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpasyncclient</artifactId>
    <version>4.1.1</version>
</dependency>

2 . demo 代码
A. 获得 request

String url = "http://localhost:8080/Baas/device/carenter.do";
HttpPost httpPost = new HttpPost(url);
//装填参数
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("third_serial_num", serialNum));
nvps.add(new BasicNameValuePair("pay_time", txTime));
nvps.add(new BasicNameValuePair("park_no", parkNo));
nvps.add(new BasicNameValuePair("plate_num", plate));
nvps.add(new BasicNameValuePair("park_start_time", startTime));
nvps.add(new BasicNameValuePair("park_end_time", endTime));
nvps.add(new BasicNameValuePair("pay_amount", amount));
nvps.add(new BasicNameValuePair("tempid", ""));
nvps.add(new BasicNameValuePair("sign", macSign));
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
return httpPost;

B. 异步

// 传入HttpPost request
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
httpclient.start();
System.out.println(" caller thread id is : " + Thread.currentThread().getId());
httpclient.execute(request, new FutureCallback<HttpResponse>() 
      @Override
    public void completed(final HttpResponse response) 
        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();
        
    
      @Override
    public void failed(final Exception ex) 
        System.out.println(request.getRequestLine() + "->" + ex);
        System.out.println(" callback thread id is : " + Thread.currentThread().getId());
    
    @Override
    public void cancelled() 
        System.out.println(request.getRequestLine() + " cancelled");
        System.out.println(" callback thread id is : " + Thread.currentThread().getId());
    

);

以上是关于Java通过httpClient同步异步发送请求的主要内容,如果未能解决你的问题,请参考以下文章

jdk11新特性——标准Java异步HTTP客户端

交易订单请求同步转异步的一种解决办法

异步httpclient(httpasyncclient)的使用与总结

java中同步和异步有啥异同?

同步并发 HttpClient 使用

JAVA通过HttpClient发送HTTP请求的方法