• 【Web】Apache HttpClient & HttpAsyncClient


    参考:https://www.baeldung.com/category/http/tag/httpclient/

    POM配置

    <dependency>
         <groupId>org.apache.httpcomponents</groupId>
         <artifactId>httpclient</artifactId>
         <version>4.5.7</version>
    </dependency>
    <dependency>
         <groupId>org.apache.httpcomponents</groupId>
         <artifactId>httpasyncclient</artifactId>
         <version>4.1.4</version> 
    </dependency>

    一、对接参数:连接超时参数

    • Connection Timeout (http.connection.timeout) – the time to establish the connection with the remote host
    • Socket Timeout (http.socket.timeout) – the time waiting for data – after establishing the connection; maximum time of inactivity between two data packets
    • the Connection Manager Timeout (http.connection-manager.timeout) – the time to wait for a connection from the connection manager/pool
    int timeout = 5;
    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(timeout * 1000)
            .setConnectionRequestTimeout(timeout * 1000)
            .setSocketTimeout(timeout * 1000)
            .build();
    CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

    HttpGet getMethod = new HttpGet("http://host:8080/path");
    HttpResponse response = httpClient.execute(getMethod);
    System.out.println( "HTTP Status of response: " + response.getStatusLine().getStatusCode());

    二、Header配置

      Since HttpClient 4.3: 通过RequestBuilder::setHeader

    HttpClient client = HttpClients.custom().build();
    HttpUriRequest request = RequestBuilder.get()
      .setUri(SAMPLE_URL)
      .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
      .build();
    client.execute(request);

      Before 4.3:  Request.setHeader

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(SAMPLE_URL);
    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    client.execute(request);

      设置默认Header,避免每个请求都重复设置,configure it as a default header on the Client

    Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    List<Header> headers = Lists.newArrayList(header);
    HttpClient client = HttpClients.custom().setDefaultHeaders(headers).build();
    HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();
    client.execute(request);

    三、请求参数

      1. 查询的QueryParam

    HttpGet httpGet = new HttpGet("https://example.com");
    URI uri = new URIBuilder(httpGet.getURI())
          .addParameter("param1", "value1")
          .addParameter("param2", "value2")
          .build();
    ((HttpRequestBase) httpGet).setURI(uri);
    CloseableHttpResponse response
    = client.execute(httpGet); client.close();

      或  BasicNameValuePair

    List nameValuePairs = new ArrayList();
    nameValuePairs.add(new BasicNameValuePair("param1", "value1"));
    nameValuePairs.add(new BasicNameValuePair("param2", "value2"));
    HttpGet httpGet = new HttpGet("https://example.com");
    URI uri = new URIBuilder(httpGet.getURI())
          .addParameters(nameValuePairs)
          .build();
    ((HttpRequestBase) httpGet).setURI(uri);
    CloseableHttpResponse response
    = client.execute(httpGet); client.close();

    四、POST的entity URL编码

    public CloseableHttpResponse sendHttpRequest() {
        List nameValuePairs = new ArrayList();
        nameValuePairs.add(new BasicNameValuePair("param1", "value1"));
        nameValuePairs.add(new BasicNameValuePair("param2", "value2"));
        HttpPost httpPost = new HttpPost("https://example.com");
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8));
        CloseableHttpResponse response = client.execute(httpPost);
        client.close();

    五、HttpAsyncClient

      1、基础使用

    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();  // 必须先执行start()
    HttpGet request = new HttpGet("http://www.google.com");
        
    Future<HttpResponse> future = client.execute(request, null);
    HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();

      2、多线程使用: PoolingNHttpClientConnectionManager

    @Test
    public void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
        ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
        PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
    CloseableHttpAsyncClient client
    = HttpAsyncClients.custom().setConnectionManager(cm).build(); client.start(); String[] toGet = { "http://www.google.com/", "http://www.apache.org/", "http://www.bing.com/" }; GetThread[] threads = new GetThread[toGet.length]; for (int i = 0; i < threads.length; i++) { HttpGet request = new HttpGet(toGet[i]); threads[i] = new GetThread(client, request); } for (GetThread thread : threads) { thread.start(); } for (GetThread thread : threads) { thread.join(); } } static class GetThread extends Thread { private CloseableHttpAsyncClient client; private HttpContext context; private HttpGet request; public GetThread(CloseableHttpAsyncClient client,HttpGet req){ this.client = client; context = HttpClientContext.create(); this.request = req; } @Override public void run() { try { Future<HttpResponse> future = client.execute(request, context, null); HttpResponse response = future.get(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } catch (Exception ex) { System.out.println(ex.getLocalizedMessage()); } } }

      3. 通过代理

    @Test
    public void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
        CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
        client.start();
        
        HttpHost proxy = new HttpHost("74.50.126.248", 3127);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet request = new HttpGet("https://issues.apache.org/");
        request.setConfig(config);
        
        Future<HttpResponse> future = client.execute(request, null);
        HttpResponse response = future.get();
        
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        client.close();
    }

      4. SSLCertificate

    public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] certificate,  String authType) {
                return true;
            }
        };
        SSLContext sslContext = SSLContexts.custom()
          .loadTrustMaterial(null, acceptingTrustStrategy).build();
    
        CloseableHttpAsyncClient client = HttpAsyncClients.custom()
          .setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
          .setSSLContext(sslContext).build();
        client.start();
        
        HttpGet request = new HttpGet("https://mms.nw.ru/");
        Future<HttpResponse> future = client.execute(request, null);
        HttpResponse response = future.get();
        
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        client.close();
    }

      5. Cookie

    public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
        BasicCookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
        cookie.setDomain(".github.com");
        cookie.setPath("/");
        cookieStore.addCookie(cookie);
        
        CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
        client.start();
        
        HttpGet request = new HttpGet("http://www.github.com");
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
        Future<HttpResponse> future = client.execute(request, localContext, null);
        HttpResponse response = future.get();
        
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        client.close();
    }

      6. 鉴权 CredentialsProvider 

    public void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials("user", "pass");
        provider.setCredentials(AuthScope.ANY, creds);
        
        CloseableHttpAsyncClient client = 
          HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
        client.start();
        
        HttpGet request = new HttpGet("http://localhost:8080");
        Future<HttpResponse> future = client.execute(request, null);
        HttpResponse response = future.get();
        
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        client.close();
    }

       7. execute接口定义:部分定义如下。

         

     关键 FutureCallback接口,定义响应完成,失败,或取消的回调处理。

        

  • 相关阅读:
    Branching / Tagging
    Working with JSON in C# & VB
    Web API 入门指南
    #进阶系列——WebApi 身份认证解决方案:Basic基础认证
    springboot与shiro在html中使用shiro标签
    springboot与shiro和mybatis和mysql
    springboot和solr结合测试使用
    springboot没有webapp目录——手动添加
    谷歌浏览器不能安装离线插件——可行方法
    elasticsearch7.1.1【win】下载安装
  • 原文地址:https://www.cnblogs.com/clarino/p/15234974.html
Copyright © 2020-2023  润新知