zoukankan      html  css  js  c++  java
  • java实现 http请求的同步和异步发送

    http同步请求 一般使用httpClient实现

     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();
    }
    

      

    http异步请求

    1.通过httpAsncClient实现

    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.concurrent.FutureCallback;
    import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
    import org.apache.http.impl.nio.client.HttpAsyncClients;
    import org.apache.http.util.EntityUtils;
    
    import java.io.IOException;
    import java.util.concurrent.CountDownLatch;
    
    public class Main {
        public static void main(String[] argv) {
            CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
            httpclient.start();
    
            final CountDownLatch latch = new CountDownLatch(1);
            final HttpGet request = new HttpGet("https://www.alipay.com/");
    
            System.out.println(" caller thread id is : " + Thread.currentThread().getId());
    
            httpclient.execute(request, new FutureCallback<HttpResponse>() {
           @Override
                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();
                    }
                }
           @Override
                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + ex);
                    System.out.println(" callback thread id is : " + Thread.currentThread().getId());
                }
           @Override
                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) {
    
            }
        }
    }
    

      

    2.还是通过同步请求,但是另起一个线程来计时,这种本质上有一个线程始终在堵塞,等待web端资源的返回。

    HttpClient包中,三个设置超时的地方:

    /* 从连接池中取连接的超时时间*/ 
    ConnManagerParams.setTimeout(params, 1000); 
    /*连接超时*/ 
    HttpConnectionParams.setConnectionTimeout(params, 2000); 
    /*请求超时*/
    HttpConnectionParams.setSoTimeout(params, 4000);

    ConnectionPoolTimeout:
    定义了从ConnectionManager管理的连接池中取出连接的超时时间。
    出错会抛出ConnectionPoolTimeoutException

    ConnectionTimeout:  
    定义了通过网络与server建立连接的超时时间,Httpclient包中通过一个异步线程去创建与server的socket连接,这就是该socket连接的超时时间。
    当连接HTTPserver或者等待HttpConnectionManager管理的一个有效连接超时出错会抛出ConnectionTimeoutException

    SocketTimeout:    
    这定义了Socket读数据的超时时间,即从server获取响应数据须要等待的时间。
    当读取或者接收Socket超时会抛出SocketTimeoutException

    httpClient 请求头设置:

    Accept、Connection、User-Agent

    Accept:表示浏览器可以接收到的类型

    */*:表示所有类型

    Connection:分为两种串行连接、持久连接(keep-alive)、管道化持久连接

    1.串行连接中,每次交互都要打开关闭连接

    2.持久连接中,第一次交互会打开连接,交互结束后连接并不关闭,下次交互就省去了建立连接的过程。

    3.管道化持久连接,允许在持久连接的基础上,可选的使用传输管道,消除传输时延。

    User-Agent:用户

  • 相关阅读:
    包装类型
    int 和 Integer 有什么区别
    final finally finalize区别
    java关键字final 有什么用?
    String和StringBuffer、StringBuilder的区别是什么?
    String 类的常用方法都有那些?
    Vue官网教程-计算属性和监听器
    Vue官网教程-模板语法
    Vue官网教程-实例
    Vue官网教程-介绍
  • 原文地址:https://www.cnblogs.com/pass-ion/p/14073468.html
Copyright © 2011-2022 走看看