欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > Apache HttpClient使用

Apache HttpClient使用

2025/3/28 23:49:01 来源:https://blog.csdn.net/qq_60275529/article/details/146498594  浏览:    关键词:Apache HttpClient使用

一、Apache HttpClient 基础版

HttpClients 是 Apache HttpClient 库中的一个工具类,用于创建和管理 HTTP 客户端实例。Apache HttpClient 是一个强大的 Java HTTP 客户端库,用于发送 HTTP 请求并处理 HTTP 响应。HttpClients 提供了多种方法来创建和配置 HTTP 客户端实例。

以下是关于 HttpClients 的详细讲解:

1. Apache HttpClient 简介

Apache HttpClient 是一个开源的 Java HTTP 客户端库,支持 HTTP/1.1 和 HTTP/2 协议。它提供了丰富的功能,例如:

  • 发送 GET、POST、PUT、DELETE 等 HTTP 请求。

  • 处理 HTTP 请求和响应的头部、状态码、实体等。

  • 支持连接池、重试机制、代理、SSL/TLS 等高级功能。

2. HttpClients 类的作用

HttpClients 是一个工厂类,用于创建 CloseableHttpClient 实例。CloseableHttpClient 是 HTTP 客户端的主要接口,用于执行 HTTP 请求。

HttpClients 提供了多种静态方法来创建和配置 HTTP 客户端实例,例如:

  • 创建默认的 HTTP 客户端。

  • 创建自定义配置的 HTTP 客户端。

  • 创建支持连接池的 HTTP 客户端。


3. HttpClients 的常用方法

(1) HttpClients.createDefault()
  • 功能: 创建一个默认的 HTTP 客户端实例。

  • 特点

    • 使用默认的配置(例如连接池、重试机制等)。

    • 适合大多数简单的 HTTP 请求场景。

  • 示例

    CloseableHttpClient httpClient = HttpClients.createDefault();
(2) HttpClients.createSystem()
  • 功能: 创建一个基于系统属性的 HTTP 客户端实例。

  • 特点

    • 使用系统属性(例如代理设置、超时时间等)来配置客户端。

    • 适合需要与系统配置集成的场景。

  • 示例

    CloseableHttpClient httpClient = HttpClients.createSystem();
(3) HttpClients.custom()
  • 功能: 返回一个 HttpClientBuilder 对象,用于自定义配置 HTTP 客户端。

  • 特点

    • 可以设置连接池、超时时间、代理、SSL/TLS 等高级配置。

    • 适合需要精细控制的场景。

  • 示例

     CloseableHttpClient httpClient = HttpClients.custom().setMaxConnTotal(100) // 最大连接数.setMaxConnPerRoute(10) // 每个路由的最大连接数.build();

4. HttpClients 的使用示例

以下是一个完整的示例,展示如何使用 HttpClients 发送 HTTP GET 请求并处理响应:

 import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;​public class HttpClientExample {public static void main(String[] args) {// 1. 创建 HTTP 客户端try (CloseableHttpClient httpClient = HttpClients.createDefault()) {// 2. 创建 HTTP GET 请求HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1");​// 3. 发送请求并获取响应try (CloseableHttpResponse response = httpClient.execute(request)) {// 4. 检查响应状态码int statusCode = response.getStatusLine().getStatusCode();System.out.println("Status Code: " + statusCode);​// 5. 获取响应内容String responseBody = EntityUtils.toString(response.getEntity());System.out.println("Response Body: " + responseBody);}} catch (Exception e) {e.printStackTrace();}}}

5. HttpClients 的高级配置

通过 HttpClients.custom() 方法,可以自定义 HTTP 客户端的配置。以下是一些常见的配置选项:

(1) 连接池配置
 CloseableHttpClient httpClient = HttpClients.custom().setMaxConnTotal(100) // 最大连接数.setMaxConnPerRoute(10) // 每个路由的最大连接数.build();
(2) 超时配置
 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 连接超时时间.setSocketTimeout(5000) // 读取超时时间.build();​CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
(3) 代理配置
 HttpHost proxy = new HttpHost("proxy.example.com", 8080);​CloseableHttpClient httpClient = HttpClients.custom().setProxy(proxy).build();
(4) SSL/TLS 配置
 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial((chain, authType) -> true) // 信任所有证书.build();​CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();

6. 注意事项

  1. 资源释放CloseableHttpClientCloseableHttpResponse 都实现了 Closeable 接口,使用后需要关闭以释放资源。

  2. 线程安全CloseableHttpClient 是线程安全的,可以在多线程环境中共享。

  3. 性能优化: 使用连接池和合理的超时配置可以显著提升性能。


7. 总结

  • HttpClients 是 Apache HttpClient 库中的一个工具类,用于创建和管理 HTTP 客户端实例。

  • 它提供了多种方法来创建默认或自定义配置的 HTTP 客户端。

  • 通过 HttpClients.custom() 方法,可以实现连接池、超时、代理、SSL/TLS 等高级配置。

  • 使用 Apache HttpClient 可以轻松发送 HTTP 请求并处理响应,是 Java 中处理 HTTP 请求的强大工具。

二、Apache HttpClient 高级版

1. HttpClients 类概述

HttpClients 是 Apache HttpClient 库中的一个工厂类,用于创建和配置 CloseableHttpClient 实例。它是构建 HTTP 客户端的入口点,支持高度自定义的 HTTP 请求处理,包括连接池管理、SSL/TLS 配置、重试机制等。


2. 核心方法与配置

2.1 创建默认客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
  • 特点

    • 使用默认的配置(连接池、请求重试等)。

    • 适合简单场景,但扩展性有限。

2.2 自定义配置客户端

通过 HttpClients.custom() 返回 HttpClientBuilder,允许精细化配置:

 CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)  // 连接池管理.setDefaultRequestConfig(requestConfig)   // 请求超时配置.setRetryHandler(retryHandler)            // 请求重试策略.setProxy(proxy)                          // 代理设置.setSSLContext(sslContext)                // SSL/TLS 配置.build();

3. 高级配置详解

3.1 连接池管理

连接池是提升性能的关键组件,避免频繁创建和销毁连接。

 PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();connectionManager.setMaxTotal(200);          // 最大总连接数connectionManager.setDefaultMaxPerRoute(20); // 每个路由(目标主机)的最大连接数​CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
3.2 超时配置
 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)    // 连接建立超时时间(毫秒).setSocketTimeout(10000)     // 数据传输超时时间(毫秒).setConnectionRequestTimeout(2000) // 从连接池获取连接的超时时间.build();​CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
3.3 重试机制

自动重试失败的请求(例如网络波动导致失败):

 HttpRequestRetryHandler retryHandler = (exception, executionCount, context) -> {if (executionCount >= 3) return false; // 最大重试次数if (exception instanceof NoHttpResponseException) return true; // 无响应时重试return false;};​CloseableHttpClient httpClient = HttpClients.custom().setRetryHandler(retryHandler).build();
3.4 代理配置
 HttpHost proxy = new HttpHost("proxy.example.com", 8080);CloseableHttpClient httpClient = HttpClients.custom().setProxy(proxy).build();
3.5 SSL/TLS 配置

信任所有证书(仅限测试环境):

 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial((chain, authType) -> true) // 信任所有证书.build();​CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) // 跳过主机名验证.build();
3.6 认证机制

使用 Basic 认证:

 CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(new AuthScope("host.example.com", 80),new UsernamePasswordCredentials("user", "pass"));​CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();

4. 请求与响应处理

4.1 发送 GET 请求
 HttpGet httpGet = new HttpGet("https://api.example.com/data");try (CloseableHttpResponse response = httpClient.execute(httpGet)) {int statusCode = response.getStatusLine().getStatusCode();HttpEntity entity = response.getEntity();String content = EntityUtils.toString(entity);EntityUtils.consume(entity); // 确保资源释放}
4.2 发送 POST 请求(JSON 数据)
 HttpPost httpPost = new HttpPost("https://api.example.com/create");StringEntity jsonEntity = new StringEntity("{\"key\":\"value\"}", ContentType.APPLICATION_JSON);httpPost.setEntity(jsonEntity);​try (CloseableHttpResponse response = httpClient.execute(httpPost)) {// 处理响应...}
4.3 文件上传(Multipart)
 HttpPost httpPost = new HttpPost("https://api.example.com/upload");FileBody fileBody = new FileBody(new File("path/to/file"));MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", fileBody).addTextBody("comment", "File upload");httpPost.setEntity(builder.build());

5. 高级功能

5.1 异步请求

使用 HttpAsyncClients 实现异步非阻塞请求:

 CloseableHttpAsyncClient asyncClient = HttpAsyncClients.custom().build();asyncClient.start();​SimpleHttpRequest request = SimpleHttpRequest.get("https://api.example.com/data");Future<SimpleHttpResponse> future = asyncClient.execute(request, new FutureCallback<>() {@Overridepublic void completed(SimpleHttpResponse response) {System.out.println("Response: " + response.getBodyText());}​@Overridepublic void failed(Exception ex) {ex.printStackTrace();}​@Overridepublic void cancelled() {System.out.println("Request cancelled");}});
5.2 请求拦截器

添加自定义逻辑(如日志记录、修改请求头):

 CloseableHttpClient httpClient = HttpClients.custom().addInterceptorFirst((HttpRequestInterceptor) (request, context) -> {request.addHeader("X-Custom-Header", "value");System.out.println("Request URI: " + request.getRequestLine().getUri());}).build();
5.3 Cookie 管理

自动管理 Cookie:

 CookieStore cookieStore = new BasicCookieStore();CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

6. 最佳实践与常见问题

6.1 资源释放

确保关闭 CloseableHttpClientCloseableHttpResponse

 try (CloseableHttpClient httpClient = HttpClients.createDefault()) {try (CloseableHttpResponse response = httpClient.execute(request)) {// 处理响应...}}
6.2 性能调优
  • 连接池参数:根据并发需求调整 MaxTotalDefaultMaxPerRoute

  • 超时设置:避免因网络问题导致线程阻塞。

  • 重用连接:复用 HttpClient 实例而非频繁创建。

6.3 错误处理
  • 重试策略:针对可恢复错误(如超时)配置自动重试。

  • 异常捕获:处理 IOExceptionClientProtocolException 等。

6.4 安全性
  • 生产环境禁用信任所有证书:使用有效 CA 签名的证书。

  • 敏感信息保护:避免在日志中打印请求头或响应体中的敏感数据。


7. 典型应用场景

  1. 微服务间通信:在分布式系统中通过 HTTP 调用其他服务。

  2. API 集成:调用第三方 RESTful API(如支付网关、地图服务)。

  3. 爬虫开发:抓取网页内容并解析数据。

  4. 文件传输:上传/下载文件到远程服务器。

  5. 测试自动化:模拟客户端发送 HTTP 请求验证接口功能。


8. 官方文档与资源

  • Apache HttpClient 官方文档: Apache HttpComponents – HttpClient Overview

  • GitHub 仓库: https://github.com/apache/httpcomponents-client


版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词