httpclient4.5实现get、post请求

本文介绍了如何在Spring Boot应用中使用Apache HttpClient进行GET和POST请求,包括参数处理和错误处理。关键代码展示了如何配置连接超时和请求头,并处理响应数据。

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

1. pom.xml

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
	<version>2.3.6.RELEASE</version>
</dependency>

<!--projectLombok Slf4j-->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.18.12</version>
</dependency>

<!--org.apache.httpcomponents/httpclient-->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.13</version>
</dependency>

2. src

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author dzp
 */
@Slf4j
@Component
public class HttpUtil {

    /**
     * Http的get请求
     *
     * @param url           url
     * @param paramList     get请求参数列表
     * @param interfaceName 接口名称
     * @return Http响应字符串
     */
    public String doGet(String url, List<String> paramList, String interfaceName) {

        // restful: ip:port/.../arg0/arg1/arg2...
        if (!CollectionUtils.isEmpty(paramList)) {
            StringBuilder sb = new StringBuilder(url);
            paramList.forEach(e -> sb.append("/").append(e));
            url = sb.toString();
        }

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            // 创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            // 配置请求参数实例
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接主机服务超时时间
                    .setConnectTimeout(1000 * 60 * 10)
                    // 设置连接请求超时时间
                    .setConnectionRequestTimeout(1000 * 60 * 10)
                    // 设置读取数据连接超时时间
                    .setSocketTimeout(1000 * 60 * 15)
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);

            // httpClient对象执行get请求,并返回响应参数对象
            long startTime = System.currentTimeMillis();
            httpResponse = httpClient.execute(httpGet);
            long endTime = System.currentTimeMillis();

            // 从响应对象中获取响应内容
            // 请求响应码
            int resultCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity entity = httpResponse.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            String result = EntityUtils.toString(entity);

            log.info("\n调用http的get请求, url: {}, 接口名称: {}, 响应参数: {}, 调用时长: {}",
                    url, interfaceName, result, (endTime - startTime) / 1000.0);

            // 处理返回的数据
            handleResponseData(startTime, endTime, resultCode, result);
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            // 关闭资源
            closeResources(httpClient, httpResponse);
        }

    }

    /**
     * Http的post请求
     *
     * @param url              url
     * @param reqParamsJsonStr post请求参数的json字符串
     * @param interfaceName    接口名称
     * @return Http响应字符串
     */
    public String doPost(String url, String reqParamsJsonStr, String interfaceName) {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            // 创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpPost远程连接实例
            HttpPost httpPost = new HttpPost(url);
            // 配置请求参数实例
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接主机服务超时时间
                    .setConnectTimeout(1000 * 60 * 10)
                    // 设置连接请求超时时间
                    .setConnectionRequestTimeout(1000 * 60 * 10)
                    // 设置读取数据连接超时时间
                    .setSocketTimeout(1000 * 60 * 15)
                    .build();
            // 为httpPost实例设置配置
            httpPost.setConfig(requestConfig);

            // 为httpPost设置封装好的请求参数
            if (!StringUtils.isEmpty(reqParamsJsonStr)) {
                StringEntity entityParam = new StringEntity(reqParamsJsonStr, "UTF-8");
                entityParam.setContentEncoding("UTF-8");
                entityParam.setContentType("application/json");
                httpPost.setEntity(entityParam);
            }

            // httpClient对象执行post请求,并返回响应参数对象
            long startTime = System.currentTimeMillis();
            httpResponse = httpClient.execute(httpPost);
            long endTime = System.currentTimeMillis();

            // 从响应对象中获取响应内容
            // 请求响应码
            int resultCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity entity = httpResponse.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            String result = EntityUtils.toString(entity);

            log.info("\n调用http的post请求, url: {}, 接口名称: {}, 请求参数:{}, 响应参数: {}, 调用时长: {}",
                    url, interfaceName, reqParamsJsonStr, result, (endTime - startTime) / 1000.0);

            // 处理返回的数据
            handleResponseData(startTime, endTime, resultCode, result);
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            // 关闭资源
            closeResources(httpClient, httpResponse);
        }
    }

    /**
     * 处理http响应的数据
     *
     * @param startTime  时间戳
     * @param endTime    时间戳
     * @param resultCode http状态码
     * @param result     http响应结果
     */
    private void handleResponseData(long startTime, long endTime, int resultCode, String result) {
        if (resultCode != HttpStatus.SC_OK) {
            log.info("Http请求失败! Http状态码为: {}", resultCode);
            throw new IllegalStateException(String.format("Http请求失败! Http状态码为: %s", resultCode));
        }
        if (StringUtils.isEmpty(result)) {
            log.info("Http状态码为: {}, 系统无信息返回, 请确认!", resultCode);
        }
        // 请求超时处理
        if ((endTime - startTime) / 1000.0 >= 30.0) {
            // TODO:请求超时处理
            log.info("http请求超时");
        }
    }

    /**
     * 关闭资源
     *
     * @param httpClient   CloseableHttpClient
     * @param httpResponse CloseableHttpResponse
     */
    private void closeResources(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {
        if (null != httpResponse) {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != httpClient) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值