【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接口,定义响应完成,失败,或取消的回调处理。

    

 

posted @   飞翔在天  阅读(334)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示