HttpUtil

该代码实现了使用ApacheHttpClient进行HTTPGET和POST请求的方法,包括处理请求参数、设置配置、获取响应内容等功能。支持带JSON参数的POST请求和获取InputStream。

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

HttpUtil


import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.InputStream;
import java.util.Map;

@Slf4j
public class HttpClient {
    public HttpClient() {
    }

    private CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    @Autowired
    private RequestConfig config;

    /**
     * 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
     *
     * @param url 请求url
     * @return 返回结果
     * @throws Exception 异常抛出
     */
    public String doGet(String url) {
        try {
            // 声明 http get 请求
            HttpGet httpGet = new HttpGet(url);
            // 装载配置信息
            httpGet.setConfig(config);
            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpGet);
            if (response != null) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param url 请求url
     * @param map 请求参数
     * @return 返回结果
     * @throws Exception 异常抛出
     */
    public String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);
        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }
        // 调用不带参数的get请求
        return this.doGet(uriBuilder.build().toString());
    }

    /**
     * 不带参数post请求
     *
     * @param url 请求url
     * @return 返回结果
     * @throws Exception 异常抛出
     */
    public String doPost(String url) throws Exception {
        return this.doPost(url, "");
    }

    /**
     * 带Json参数的Post请求
     *
     * @param url       请求url
     * @param jsonParam json字符串
     * @return 返回结果
     * @throws Exception 异常抛出
     */
    public String doPost(String url, String jsonParam) throws Exception {
        String result = "";
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Accept-Encoding", "UTF-8");

        StringEntity s = new StringEntity(jsonParam, "UTF-8");
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");
        httpPost.setEntity(s);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
        }

        return result;
    }

    public InputStream getInputStream(String url, String jsonParam) throws Exception {
        String result = "";
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        httpPost.setHeader("Content-Type", "application/json");
        if (jsonParam.length() > 0) {
            httpPost.setEntity(new StringEntity(jsonParam, ContentType.create("application/json", "utf-8")));
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity.getContent();
            }
        }
        return null;
    }

}


### HttpUtil 工具类概述 HttpUtil 是用于简化 HTTP 请求操作的 Java 实用程序库。该工具类提供了便捷的方法来执行常见的 HTTP 操作,如 GETPOST 请求,并且集成了多种功能特性以增强其灵活性和可靠性[^1]。 ### 功能特点 - **超时设置**:允许开发者指定连接和读取数据的最大等待时间。 - **URL 参数处理**:能够方便地构建带有查询字符串的 URL 地址。 - **请求体格式选择**:支持不同的内容类型,特别是 JSON 格式的请求体。 - **异常处理机制**:内置了对可能出现错误情况的有效管理策略。 - **日志记录能力**:可以跟踪并记录每次网络交互过程中的重要事件。 ### Maven 依赖配置 为了使用基于 HttpClient 的 HttpUtil 类,在项目中需添加如下 Maven 依赖: ```xml <dependency> <groupId>com.seepine</groupId> <artifactId>httpclient</artifactId> <version>1.0.0</version> </dependency> ``` ### 示例代码展示 #### 发送简单的 GET 请求 下面是一个利用 HttpUtil 执行 GET 方法的例子,其中包含了如何定义目标地址以及获取响应结果的过程。 ```java public String sendGetRequest(String url) { try { HttpResponse response = HttpUtil.createGet(url).execute(); return response.body(); } catch (Exception e) { logger.error("Error occurred while sending get request", e); throw new RuntimeException(e.getMessage()); } } ``` #### 提交包含 JSON 数据的 POST 请求 此部分展示了怎样通过 PostMethod 对象发送携带 JSON 负载的数据到远程服务器端点上。 ```java public void doPostWithJsonBody(String url, Map<String, Object> params) throws Exception { HttpRequest request = HttpUtil.createPost(url) .header("Content-Type", "application/json") .body(JSON.toJSONString(params)); HttpResponse httpResponse = request.execute(); System.out.println(httpResponse.getStatusLine().getStatusCode() + ":" + httpResponse.body()); } ``` ### 日志与调试建议 当遇到问题时,启用详细的日志可以帮助定位具体原因。通常情况下,默认的日志级别可能不足以提供足够的诊断信息;因此推荐调整至更细粒度的日志输出模式以便更好地理解整个通信流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值