一、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. 注意事项
资源释放: closeablehttpclient
和 closeablehttpresponse
都实现了 closeable
接口,使用后需要关闭以释放资源。
线程安全: closeablehttpclient
是线程安全的,可以在多线程环境中共享。
性能优化: 使用连接池和合理的超时配置可以显著提升性能。
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<>() { @override public void completed(simplehttpresponse response) { system.out.println("response: " + response.getbodytext()); } @override public void failed(exception ex) { ex.printstacktrace(); } @override public 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 资源释放
确保关闭 closeablehttpclient
和 closeablehttpresponse
:
try (closeablehttpclient httpclient = httpclients.createdefault()) { try (closeablehttpresponse response = httpclient.execute(request)) { // 处理响应... } }
6.2 性能调优
- 连接池参数:根据并发需求调整
maxtotal
和defaultmaxperroute
。 - 超时设置:避免因网络问题导致线程阻塞。
- 重用连接:复用
httpclient
实例而非频繁创建。
6.3 错误处理
- 重试策略:针对可恢复错误(如超时)配置自动重试。
- 异常捕获:处理
ioexception
、clientprotocolexception
等。
6.4 安全性
- 生产环境禁用信任所有证书:使用有效 ca 签名的证书。
- 敏感信息保护:避免在日志中打印请求头或响应体中的敏感数据。
7. 典型应用场景
- 微服务间通信:在分布式系统中通过 http 调用其他服务。
- api 集成:调用第三方 restful api(如支付网关、地图服务)。
- 爬虫开发:抓取网页内容并解析数据。
- 文件传输:上传/下载文件到远程服务器。
- 测试自动化:模拟客户端发送 http 请求验证接口功能。
8. 官方文档与资源
apache httpclient 官方文档: apache httpcomponents – httpclient overview
github 仓库: https://github.com/apache/httpcomponents-client
到此这篇关于apache httpclient使用的文章就介绍到这了,更多相关apache httpclient使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论