SpringBoot中HttpClient的使用

本文介绍了如何在SpringBoot项目中使用ApacheHttpClient发送GET和POST请求,包括创建HttpClient对象、执行请求和处理响应数据的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1. HttpClient 介绍

HttpClientApache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta上很著名的另外两个开源项目 CactusHTMLUnit 都使用了 HttpClient

核心 API:

  • HttpClient
  • HttpClients
  • CloseableHttpClient
  • HttpGet
  • HttpPost

发送请求步骤:

  • 创建 HttpClient 对象
  • 创建 Http 请求对象
  • 调用 HttpClient 的 execute 方法发送请求

2. 导入坐标

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

3. 使用 HttpClient 发送 Get 请求

package com.sky.test;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class HttpClientTest {

    /**
     * 测试httpclient GET
     */
    @Test
    public void testGet() throws IOException {
        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建请求对象
        HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
        // 发送请求,接收响应
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 获取状态码
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("获取服务器返回的状态码" + statusCode);
        // 获取响应数据
        HttpEntity entity = response.getEntity();
        String body = EntityUtils.toString(entity);
        System.out.println("响应数据" + body);
        // 关闭资源
        response.close();
        httpClient.close();
    }
}

4. 使用 HttpClient 发送 Post 请求

package com.sky.test;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class HttpClientTest {

    /**
     * 测试httpclient POST
     */
    @Test
    public void testPost() throws IOException {
        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建请求对象
        HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");

        // 封装post请求
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "admin");
        jsonObject.put("password", "123456");

        StringEntity entity = new StringEntity(jsonObject.toString());
        // 指定请求编码方式
        entity.setContentEncoding("utf-8");
        // 数据格式
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        // 发送请求,接收响应
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 获取状态码
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("响应码为: " + statusCode);
        // 获取响应数据
        HttpEntity entity1 = response.getEntity();
        String body = EntityUtils.toString(entity1);
        System.out.println("响应数据" + body);
        // 关闭资源
        response.close();
        httpClient.close();
    }

}
Spring Boot使用HttpClient可以通过引入httpclient的POM依赖来实现。首先,在你的Spring Boot工程中,需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> ``` 接下来,你可以创建一个HttpClientController类,并在该类中定义不同的接口方法,如doGetNoParams和doPostNoParams。这些方法可以使用@GetMapping和@PostMapping注解来标注,分别表示GET和POST请求。例如: ```java @RestController @RequestMapping("/httpClient") public class HttpClientController { @Autowired private HttpClientService httpClientService; // GET请求接口不带参数 @GetMapping("/doGetNoParams") public String doGetNoParams() { return httpClientService.doGetNoParams(); } // POST请求接口不带参数 @PostMapping("/doPostNoParams") public String doPostNoParams() { return httpClientService.doPostNoParams(); } } ``` 在这个示例中,我们使用@Autowired将HttpClientService注入到HttpClientController中,然后在doGetNoParams和doPostNoParams方法中调用相应的HttpClientService方法来实现GET和POST请求。具体的请求逻辑可以在HttpClientService中实现。 这样,你就可以在Spring Boot使用HttpClient来进行HTTP请求了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [「HttpClient」在 SpringBoot使用 HttpClient 实现 HTTP 请求](https://blog.csdn.net/wdj0311/article/details/121598212)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值