Apache HttpClient 5 用法-Java调用http服务

Apache HttpClient 5 核心用法详解

Apache HttpClient 5 是 Apache 基金会推出的新一代 HTTP 客户端库,相比 4.x 版本在性能、模块化和易用性上有显著提升。以下是其核心用法及最佳实践:


一、添加依赖
Maven 项目:
复制代码
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.4-alpha1</version> <!-- 检查最新版本 -->
</dependency>
Gradle 项目:
复制代码
implementation 'org.apache.httpcomponents.client5:httpclient5:5.4-alpha1'

二、基础用法
1. 创建 HttpClient 实例
复制代码
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

// 创建带连接池的客户端(默认连接池大小:2*CPU核心数)
CloseableHttpClient httpClient = HttpClients.custom()
    .setConnectionManagerShared(true) // 共享连接池(推荐)
    .setDefaultRequestConfig(RequestConfig.custom()
        .setConnectTimeout(5000)   // 连接超时(毫秒)
        .setResponseTimeout(10000) // 响应超时
        .build())
    .build();
2. 发送 GET 请求
复制代码
HttpGet httpGet = new HttpGet("https://api.example.com/data");

try (CloseableHttpClient client = HttpClients.createDefault()) {
    try (CloseableHttpResponse response = client.execute(httpGet)) {
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        System.out.println("Status: " + response.getCode() + ", Body: " + result);
    }
}
3. 发送 POST 请求(提交 JSON)
复制代码
HttpPost httpPost = new HttpPost("https://api.example.com/post");
String jsonBody = "{\"key\":\"value\"}";
httpPost.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));

try (CloseableHttpClient client = HttpClients.createDefault()) {
    try (CloseableHttpResponse response = client.execute(httpPost)) {
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        System.out.println("Status: " + response.getCode() + ", Body: " + result);
    }
}

三、高级功能
1. 连接池配置(优化性能)
复制代码
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);       // 最大连接数
cm.setDefaultMaxPerRoute(20); // 每个路由默认最大连接数

CloseableHttpClient client = HttpClients.custom()
    .setConnectionManager(cm)
    .build();
复制代码
HttpGet httpGet = new HttpGet("https://api.example.com/data");
httpGet.setHeader("User-Agent", "Apache HttpClient 5");
httpGet.setHeader("Authorization", "Bearer token123");

// 添加 Cookie
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("session_id", "abc123");
cookie.setDomain("api.example.com");
cookieStore.addCookie(cookie);

CloseableHttpClient client = HttpClients.custom()
    .setDefaultCookieStore(cookieStore)
    .build();
3. 文件上传(Multipart)
复制代码
HttpPost httpPost = new HttpPost("https://api.example.com/upload");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("path/to/file.jpg"), 
    ContentType.MULTIPART_FORM_DATA, "file.jpg");
builder.addTextBody("description", "Test upload", ContentType.TEXT_PLAIN);

httpPost.setEntity(builder.build());

try (CloseableHttpClient client = HttpClients.createDefault()) {
    try (CloseableHttpResponse response = client.execute(httpPost)) {
        // 处理响应
    }
}
4. 异步请求(非阻塞)
复制代码
HttpClientAsyncClient asyncClient = HttpClients.createAsyncDefault();

HttpGet httpGet = new HttpGet("https://api.example.com/data");
asyncClient.execute(httpGet, new FutureCallback<>() {
    @Override
    public void completed(ClassicHttpResponse response) {
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        System.out.println("Async Response: " + result);
    }

    @Override
    public void failed(Exception ex) {
        ex.printStackTrace();
    }

    @Override
    public void cancelled() {
        System.out.println("Request cancelled");
    }
});

// 主线程继续执行其他任务
Thread.sleep(5000); // 等待异步结果(实际需用 CountDownLatch 等机制)

四、迁移指南(从 HttpClient 4.x)
  1. 包名变化

    • org.apache.http.client.HttpClientorg.apache.hc.client5.http.classic.HttpClient
    • HttpGet/HttpPost 等类路径调整。
  2. API 调整

    • 响应处理:CloseableHttpResponse 替代 CloseableHttpResponse(方法名类似)。
    • 连接池管理:使用 PoolingHttpClientConnectionManager 替代 PoolingHttpClientConnectionManager
  3. 移除废弃方法

    • HttpClientBuilder.setMaxConnPerRoute() 改为 setMaxConnPerRoute(Route, int)

五、最佳实践
  1. 复用 HttpClient 实例 :避免频繁创建/销毁,推荐使用 HttpClients.custom().build() 创建单例。
  2. 资源释放 :使用 try-with-resources 确保 CloseableHttpClientCloseableHttpResponse 正确关闭。
  3. 异常处理 :捕获 IOExceptionHttpRequestException,处理网络错误和 HTTP 状态码。
  4. 性能监控 :通过 ConnectionStats 监控连接池使用情况。

通过以上内容,您已掌握 Apache HttpClient 5 的核心用法,可根据项目需求实现高效、稳定的 HTTP 通信。如需处理复杂场景(如 OAuth2 认证、WebSocket),可进一步探索其扩展模块。

相关推荐
Ronin-Lotus33 分钟前
程序代码篇---python获取http界面上按钮或者数据输入
python·http
caihuayuan52 小时前
生产模式下react项目报错minified react error #130的问题
java·大数据·spring boot·后端·课程设计
编程、小哥哥2 小时前
Java大厂面试:从Web框架到微服务技术的场景化提问与解析
java·spring boot·微服务·面试·技术栈·数据库设计·分布式系统
界面开发小八哥2 小时前
「Java EE开发指南」如何使用MyEclipse的可视化JSF编辑器设计JSP?(二)
java·ide·人工智能·java-ee·myeclipse
找不到、了3 小时前
Spring-Beans的生命周期的介绍
java·开发语言·spring
caihuayuan44 小时前
React Native 0.68 安装react-native-picker报错:找不到compile
java·大数据·sql·spring·课程设计
爱编程的鱼4 小时前
C#接口(Interface)全方位讲解:定义、特性、应用与实践
java·前端·c#
旋风菠萝4 小时前
深入理解Java中的Minor GC、Major GC和Full GC
java·jvm·gc
苹果酱05674 小时前
React方向:react脚手架的使用
java·vue.js·spring boot·mysql·课程设计
找不到、了4 小时前
JVM如何处理多线程内存抢占问题
java·jvm