HTTP协议客户端之HttpClient的基本使用

心已赠人 2023-09-27 15:59 200阅读 0赞

HttpClient的基本使用

概述

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HttpClient相比JDK自带的URLConnection,增加了易用性和灵活性,使客户端发送Http请求变得更加容易,而且也方便开发测试接口,大大提高开发的效率。

常用HTTP协议客户端包括有:httpclient、restTemplate、okHttp

官网:https://hc.apache.org/index.html

5f3d7d6a953121b7046755801fb9e2c8.png

添加依赖

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.13</version>
  5. </dependency>

Get请求

1.无参数的GET请求

  1. @Test
  2. public void get() throws IOException {
  3. // 创建HttpClient对象
  4. CloseableHttpClient httpClient = HttpClients.createDefault();
  5. // 创建HttpGet请求
  6. HttpGet httpGet = new HttpGet("https://www.baidu.com");
  7. // 响应对象
  8. CloseableHttpResponse response = null;
  9. try {
  10. // 使用HttpClient发起请求
  11. response = httpClient.execute(httpGet);
  12. // 判断响应状态码是否为200
  13. if (response.getStatusLine().getStatusCode() == 200) {
  14. // 获取返回数据
  15. HttpEntity httpEntity = response.getEntity();
  16. String content = EntityUtils.toString(httpEntity, "UTF-8");
  17. // 打印数据长度
  18. log.info("content:{}", content);
  19. }
  20. } finally {
  21. // 释放连接
  22. if (response != null) {
  23. response.close();
  24. }
  25. httpClient.close();
  26. }
  27. }

2.带参数的GET请求

  1. HttpGet httpGet = new HttpGet("https://www.baidu.com/s?wd=java");

POST请求

1.无参数的POST请求

  1. @Test
  2. public void post() throws IOException {
  3. // 创建HttpClient对象
  4. CloseableHttpClient httpClient = HttpClients.createDefault();
  5. // 创建HttpGet请求
  6. HttpPost httpPost = new HttpPost("http://www.baidu.com");
  7. // 响应对象
  8. CloseableHttpResponse response = null;
  9. try {
  10. // 使用HttpClient发起请求
  11. response = httpClient.execute(httpPost);
  12. // 判断响应状态码是否为200
  13. if (response.getStatusLine().getStatusCode() == 200) {
  14. // 获取返回数据
  15. HttpEntity httpEntity = response.getEntity();
  16. String content = EntityUtils.toString(httpEntity, "UTF-8");
  17. // 打印数据长度
  18. log.info("content:{}", content);
  19. }
  20. } finally {
  21. // 释放连接
  22. if (response != null) {
  23. response.close();
  24. }
  25. httpClient.close();
  26. }
  27. }

2.带参数的POST请求

  1. public static void main(String[] args) throws Exception {
  2. // 创建HttpClient对象
  3. CloseableHttpClient httpClient = HttpClients.createDefault();
  4. // 创建HttpPost对象,设置url访问地址
  5. HttpPost httpPost = new HttpPost("https://fanyi.baidu.com/langdetect");
  6. // 声明List集合,封装表单中的参数
  7. List<NameValuePair> params = new ArrayList<NameValuePair>();
  8. // 实际请求地址:https://fanyi.baidu.com/langdetect?query=Jav

发表评论

表情:
评论列表 (有 0 条评论,200人围观)

还没有评论,来说两句吧...

相关阅读