HTTPClient基本使用
使用maven,在xml中引用
1 2 3 4 5 6 | <!-- https: //mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version> 4.5 . 2 </version> </dependency> |
第一个demo
第一个.java文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package com.httpclient.demo; import org.apache.http.HttpEntity; 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.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.testng.annotations.Test; import java.io.IOException; public class HttpClientDemo { @Test public void test01() { //创建get请求 String uri = "https://www.baidu.com" ; HttpGet get = new HttpGet(uri); //获取http客户端 CloseableHttpClient client = HttpClientBuilder.create().build(); //响应模型 CloseableHttpResponse response = null ; try { //由http客户端,发送get请求 response = client.execute(get); //从响应中,获取响应实体 HttpEntity respEntity = response.getEntity(); String result = EntityUtils.toString(respEntity, "utf-8" ); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } } } |
执行结果:
将配置文件进行优化
在项目resources目录下,建一个application.properties文件,将自己需要用的常量可以放在配置文件中
在测试类中,将配置文件引入:
@BeforeTest public void beforeClass() { //将配置文件application.properties中,加载进来 bundle = ResourceBundle.getBundle("application", Locale.CHINA); url = bundle.getString("test.url"); }
字符编码:Locale.CHINA,将配置文件中的一些中文进行兼容
这个url这个变量,定义为全局变量,先在@BeforeTest中引入,然后url这个变量就被赋值了。下面就可以继续引用了
获取Cookie
下面👇这个是另一个博主写的:https://segmentfault.com/a/1190000011142669
获取响应的状态码:
//获取响应的状态码,直接在响应response中获取 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("状态码 :" + statusCode);
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤