一、HttpClient 简介

HttpClient 是 Apache 提供的一个强大的 HTTP 通信客户端工具,广泛用于 Java 程序中发送 HTTP 请求,适合服务间调用、接口测试、模拟请求等场景。

✅ 主要特点:

  • 支持所有 HTTP 方法(GET、POST、PUT、DELETE、HEAD、OPTIONS 等)

  • 支持 HTTPS(SSL)协议

  • 支持代理服务器(如 Nginx)

  • 支持自动跳转(302 Redirect)

  • 支持连接池、重试机制、自定义请求头等扩展能力


二、Maven 依赖引入

<dependencies>
    <!-- Apache HttpClient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.5</version>
    </dependency>

    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- FastJSON(用于 JSON 解析,如果需要) -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.66</version>
    </dependency>
</dependencies>

三、封装 HttpClient 工具类

📌 HttpClientUtil.java 工具类代码

public class HttpClientUtil {

    // GET 请求(带参数)
    public static String doGet(String url, Map<String, String> param) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;

        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) response.close();
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    // GET 请求(无参数)
    public static String doGet(String url) {
        return doGet(url, null);
    }

    // POST 请求(表单参数)
    public static String doPost(String url, Map<String, String> param) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            HttpPost httpPost = new HttpPost(url);
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    // POST 请求(无参数)
    public static String doPost(String url) {
        return doPost(url, null);
    }

    // POST 请求(JSON 数据)
    public static String doPostJson(String url, String json) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
}

四、HttpClient 调用示例(Controller中使用)

@RestController
public class OrderController {

    @RequestMapping("/orderToMember1")
    public String orderToMember1() {
        // 使用 HttpClient 工具类调用远程服务
        return "订单调用会员服务返回结果:" +
               HttpClientUtil.doGet("http://127.0.0.1:8081/getMember", null);
    }
}

五、总结

问题 解答
HttpClient 是什么? Java 中用于发送 HTTP 请求的工具类库
适合场景 微服务之间通信(使用 HTTP 协议)、模拟前端请求、接口自动化测试等
与 RestTemplate、WebClient 区别 HttpClient 是底层实现,RestTemplateWebClient 是 Spring 封装的更高级客户端
支持协议 支持 HTTP 和 HTTPS,支持 GET、POST、PUT 等方法

如需更现代、更推荐的方式,可以使用:

  • Spring 的 RestTemplate(已逐渐被淘汰)

  • Spring WebFlux 的 WebClient

  • Spring Cloud 的 OpenFeign(声明式客户端)

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐