当前位置: 首页 > news >正文

工业产品设计网站推荐制作网站首页psd

工业产品设计网站推荐,制作网站首页psd,wordpress 显示名,做线上网站的风险分析Apache HttpClient 5 核心用法详解 Apache HttpClient 5 是 Apache 基金会推出的新一代 HTTP 客户端库&#xff0c;相比 4.x 版本在性能、模块化和易用性上有显著提升。以下是其核心用法及最佳实践&#xff1a; 一、添加依赖 Maven 项目&#xff1a; <dependency><…

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<>() {@Overridepublic void completed(ClassicHttpResponse response) {HttpEntity entity = response.getEntity();String result = EntityUtils.toString(entity);System.out.println("Async Response: " + result);}@Overridepublic void failed(Exception ex) {ex.printStackTrace();}@Overridepublic void cancelled() {System.out.println("Request cancelled");}
});// 主线程继续执行其他任务
Thread.sleep(5000); // 等待异步结果(实际需用 CountDownLatch 等机制)

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

    • org.apache.http.client.HttpClient → org.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 确保 CloseableHttpClient 和 CloseableHttpResponse 正确关闭。
  3. 异常处理:捕获 IOException 和 HttpRequestException,处理网络错误和 HTTP 状态码。
  4. 性能监控:通过 ConnectionStats 监控连接池使用情况。

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

http://www.dtcms.com/a/399551.html

相关文章:

  • 谷歌seo网站推广怎么做手机网站域名哪里注册时间
  • 记一次添加.h和.cpp后,编译时显示无法解析的外部符号问题
  • 宝安网站制作哪里好长阳网站建设
  • 机器学习——线性回归详解
  • Python知识体系
  • 做电商看的网站有哪些内容网站开发和ui的区别
  • 从0到1搭建灵活用工平台:一套系统需要具备哪些核心功能?
  • 【ReST】2. ReST 行内文本语法详解及与 Markdown 的区别
  • 网站 维护网站开发待遇怎么样
  • 网站建设合同怎么写开网店怎么找货源啊
  • iOS 混淆在多渠道分发场景下的实践,配置统一、符号表管理与分发安全
  • 开发区网站开发语言乌克兰俄罗斯
  • HAProxy 负载均衡器
  • 使用C#代码自定义密码加密Word
  • 报修网站模板网络营销是什么时候兴起的
  • 【Java开发:Lambda表达式】
  • tomcat启动卡在Initializing Spring root WebApplicationContext
  • 合肥建设工程交易网站石家庄学生
  • docker底层的隔离机制和资源控制机制
  • 网站建设公司源码 asp网站建设电脑和手机有区别吗
  • flash attention2 计算过程的探索和学习
  • 领域驱动设计的vo、do、dto
  • 画图软件在线纵横seo
  • 求解四阶泛函 u‘‘‘‘ - u‘‘ + f = 0 的驻点及周期性边界条件
  • VC维(Vapnik-Chervonenkis Dimension)的故事:模型复杂度的衡量
  • FM收音机RDS功能深度解析
  • 做网站运营还是翻译郑州市房产信息网官方网站
  • SM2商用密码算法轻量化技术:原理、实践与未来展望
  • 双目视觉的传统立体匹配算法有哪些?
  • 电子商务网站版面布局更改wordpress链接