Spring Boot 之httpClient使用

本文介绍如何在SpringBoot项目中使用HttpClient发起HTTP请求。主要内容包括引入相关依赖、编写工具类及业务代码调用示例。

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

超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议。所有的WWW文件都必须遵守这个标准。而HttpClient是可以支持http相关协议的工具包,它有如下功能:
1.实现了所有的http方法(GET,POST,PUT,HEAD 等)
2.支持自动转向
3.支持 HTTPS 协议
4.支持代理服务器等
既然HttpClient使用这么广泛,则本文讲解下Spring Boot 中怎么使用HttpClient.如下:
一.引入相关依赖

       <!-- http所需包 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
        </dependency>
         <!-- /http所需包 -->

         <!-- 数据解析所需包 -->   
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>   
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.4</version>
        </dependency>
        <!-- /数据解析所需包 -->   

二.编写相关工具类
写个http的工具类,以便业务代码直接调用,如下:

/**
 * Http工具类
 */
public class HttpUtils {

    /**
     * 发送POST请求
     * @param url 请求url
     * @param data 请求数据
     * @return 结果
     */
    @SuppressWarnings("deprecation")
    public static String doPost(String url, String data) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000).setConnectTimeout(20000)
                .setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);
        String context = StringUtils.EMPTY;
        if (!StringUtils.isEmpty(data)) {
            StringEntity body = new StringEntity(data, "utf-8");
            httpPost.setEntity(body);
        }
        // 设置回调接口接收的消息头
        httpPost.addHeader("Content-Type", "application/json");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            context = EntityUtils.toString(entity, HTTP.UTF_8);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                response.close();
                httpPost.abort();
                httpClient.close();
            } catch (Exception e) {
                e.getStackTrace();
            }
        }
        return context;
    }

    /**
     * 解析出url参数中的键值对
     * @param url url参数
     * @return 键值对
     */
    public static Map<String, String> getRequestParam(String url) {

        Map<String, String> map = new HashMap<String, String>();
        String[] arrSplit = null;

        // 每个键值为一组
        arrSplit = url.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            // 解析出键值
            if (arrSplitEqual.length > 1) {
                // 正确解析
                map.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (arrSplitEqual[0] != "") {
                    map.put(arrSplitEqual[0], "");
                }
            }
        }
        return map;
    }
}

三.业务代码中使用
业务中代码使用,拼装请求Url和请求数据,就可以调用工具类里的doPost()方法开始直接使用咯。如下:

private String getFileStorePath(String courtId, String seesionId){
        String fileStorePath = StringUtils.EMPTY;
        //请求参数
        String data = "{\"courtId\":\"" + courtId + "\",\"sessionId\":\"" + seesionId + "\"}";
        String fileServiceUrl="http://111.11.11.11:8086";
        //发送请求,获取结果
        String result = HttpUtils.doPost(fileServiceUrl + "/ms-service/voice/search", data);    
        if(StringUtils.isNotBlank(result)){
            com.alibaba.fastjson.JSONObject jsonobject = JSON.parseObject(result);
            fileStorePath = jsonobject.getString("path");
            logger.info("fileStorePath = " + fileStorePath);
        }
        return fileStorePath;
    }

如有不当之处,烦请斧正,一起沟通。

### Spring Boot 中 RestTemplate 使用 HttpClient5 配置不生效的原因分析 在 Spring Boot 应用程序中,当尝试通过 `RestTemplate` 结合 Apache HttpClient 5 进行 HTTP 请求时,可能会遇到配置未生效的情况。以下是可能原因及其解决方案。 #### 可能原因一:依赖冲突 如果项目中的 Maven 或 Gradle 文件存在多个版本的 HttpClient 和相关库,则可能导致加载错误或覆盖默认实现。建议检查项目的依赖树并清理冗余项[^3]。 ```xml <dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> <version>5.x.x</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 确保使用HttpClient 版本与 Spring Boot 的兼容性一致。例如,在 Spring Boot 2.4.x 中推荐使用 HttpClient 4.x;而更高版本则支持 HttpClient 5.x。 --- #### 可能原因二:自定义 Bean 定义缺失 Spring Boot 默认会创建一个基于 JDK URLConnection 实现的 `RestTemplate`。为了切换到 HttpClient 5,需显式声明一个定制化的 `RestTemplate` Bean 并注入所需的工厂类[^1]。 以下是一个完整的配置示例: ```java import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.client5.http.ssl.SSLContextBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @Configuration public class RestClientConfig { @Bean public CloseableHttpClient httpClient() { try { SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial((chain, authType) -> true).build(); return HttpClients.custom() .setSSLContext(sslContext) .build(); } catch (Exception e) { throw new RuntimeException("Failed to create HttpClient", e); } } @Bean public RestTemplate restTemplate(CloseableHttpClient httpClient) { HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); return new RestTemplate(factory); } } ``` 此代码片段展示了如何将 Apache HttpClient 5 整合至 Spring Boot,并替换默认的 `RestTemplate` 工厂实现。 --- #### 可能原因三:自动装配机制失效 某些情况下,即使提供了正确的 Bean 定义,仍可能出现自动装配失败的现象。这通常是因为其他组件(如 WebClient)抢占了优先级较高的客户端实例。可以通过强制指定 `@Primary` 注解来解决问题[^2]。 更新后的配置如下所示: ```java @Bean @Primary public RestTemplate restTemplate(CloseableHttpClient httpClient) { HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); return new RestTemplate(factory); } ``` --- #### 测试验证方法 完成上述调整后,可通过单元测试验证新配置是否正常工作。例如: ```java @SpringBootTest class RestTemplateTest { @Autowired private RestTemplate restTemplate; @Test void testCustomRestTemplate() { String url = "https://example.com/api/test"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); assertNotNull(response); assertEquals(HttpStatus.OK.value(), response.getStatusCodeValue()); } } ``` --- #### 总结 综上所述,解决 Spring Boot 中 `RestTemplate` 使用 HttpClient 5 配置不生效的问题主要涉及以下几个方面: 1. 清理依赖冲突; 2. 显式定义自定义 `RestTemplate` Bean; 3. 调整自动装配顺序以确保正确加载所需实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值