HTTP协议客户端之HttpClient的基本使用
HttpClient的基本使用
概述
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
HttpClient相比JDK自带的URLConnection,增加了易用性和灵活性,使客户端发送Http请求变得更加容易,而且也方便开发测试接口,大大提高开发的效率。
常用HTTP协议客户端包括有:httpclient、restTemplate、okHttp
官网:https://hc.apache.org/index.html
添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
Get请求
1.无参数的GET请求
@Test
public void get() throws IOException {
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpGet请求
HttpGet httpGet = new HttpGet("https://www.baidu.com");
// 响应对象
CloseableHttpResponse response = null;
try {
// 使用HttpClient发起请求
response = httpClient.execute(httpGet);
// 判断响应状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 获取返回数据
HttpEntity httpEntity = response.getEntity();
String content = EntityUtils.toString(httpEntity, "UTF-8");
// 打印数据长度
log.info("content:{}", content);
}
} finally {
// 释放连接
if (response != null) {
response.close();
}
httpClient.close();
}
}
2.带参数的GET请求
HttpGet httpGet = new HttpGet("https://www.baidu.com/s?wd=java");
POST请求
1.无参数的POST请求
@Test
public void post() throws IOException {
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpGet请求
HttpPost httpPost = new HttpPost("http://www.baidu.com");
// 响应对象
CloseableHttpResponse response = null;
try {
// 使用HttpClient发起请求
response = httpClient.execute(httpPost);
// 判断响应状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 获取返回数据
HttpEntity httpEntity = response.getEntity();
String content = EntityUtils.toString(httpEntity, "UTF-8");
// 打印数据长度
log.info("content:{}", content);
}
} finally {
// 释放连接
if (response != null) {
response.close();
}
httpClient.close();
}
}
2.带参数的POST请求
public static void main(String[] args) throws Exception {
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost对象,设置url访问地址
HttpPost httpPost = new HttpPost("https://fanyi.baidu.com/langdetect");
// 声明List集合,封装表单中的参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 实际请求地址:https://fanyi.baidu.com/langdetect?query=Jav
还没有评论,来说两句吧...