阐述使用 HttpClient 进行 http 请求

1 概述

(1)HTTPClient 实现了所有 HTTP 的方法(包括 GET、POST、PUT、DELETE、OPTIONS

等),使用该工具包可以很方便的发起http请求。

(2)Maven 依赖

bash 复制代码
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3</version>
</dependency>

(3)执行http请求的步骤如下:

  • 创建 HttpClient 实例
  • 创建请求实例(如 HttpGet)
  • 执行请求
  • 处理响应结果
  • 关闭连接(释放资源)

2 Http接口案例

下面是几个 Http 接口。后续接口调用案例将调用下述接口。

java 复制代码
@RestController
@RequestMapping("/request")
public class RequestTestController {


    @GetMapping("/getWithoutParam")
    public String getWithoutParam() {
        return "data_getWithoutParam";
    }

    @GetMapping("/getWithParam")
    public String getWithParam(String param, String param2) {
        return "data_getWithParam_" + param + "_" + param2;
    }

    @PostMapping("/postWithoutParam")
    public String postWithoutParam() {
        return "data_postWithoutParam";
    }

    @PostMapping("/postWithParam")
    public String postWithParam(@RequestBody PostWithParamDto param) {
        return "data_postWithParam_" + param.getParam() + "_" + param.getParam2();
    }

    @Data
    public static class PostWithParamDto {
        private String param;
        private String param2;
    }

}

3 get请求

下面是 get 请求的调用方式,分别为调用无入参和有入参的 get 接口。

3.1 get 无参

java 复制代码
    /**
     * get 无参
     */
    public void getWithoutParam() {
        CloseableHttpResponse response = null;
        // 创建 httpClient 实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建请求实例
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/request/getWithoutParam");
        try {
            // 执行请求
            response = httpClient.execute(httpGet);
            // 处理响应结果
            if (response.getStatusLine().getStatusCode() != 200) {
                log.error("http getWithoutParam error. response:{}", JSON.toJSONString(response));
                return;
            }

            String resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            log.info("http getWithoutParam result:{}", JSON.toJSONString(resultString));
        } catch (Exception e) {
            log.error("http getWithoutParam error", e);
        } finally {
            // 关闭连接
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (Exception e) {
                log.error("http getWithoutParam error", e);
            }
        }
    }

3.2 get 有参

java 复制代码
    public void getWithParam() {
        CloseableHttpResponse response = null;
        // 创建 httpClient 实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建请求实例
        StringBuilder stringBuilder = new StringBuilder();
        try {
            stringBuilder.append("param=").append(URLEncoder.encode("123", "utf-8"));
            stringBuilder.append("&");
            stringBuilder.append("param2=").append(URLEncoder.encode("456", "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/request/getWithParam?"+stringBuilder);
        try {
            // 执行请求
            response = httpClient.execute(httpGet);
            // 处理响应结果
            if (response.getStatusLine().getStatusCode() != 200) {
                log.error("http getWithParam error. response:{}", JSON.toJSONString(response));
                return;
            }

            String resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            log.info("http getWithParam result:{}", JSON.toJSONString(resultString));
        } catch (Exception e) {
            log.error("http getWithParam error", e);
        } finally {
            // 关闭连接
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (Exception e) {
                log.error("http getWithParam error", e);
            }
        }
    }

4 post 请求

下面是 post 请求的调用方式,分别为调用无入参和有入参的 post 接口。

4.1 post 无参

java 复制代码
    public void postWithoutParam() {
        CloseableHttpResponse response = null;
        // 创建 httpClient 实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建请求实例
        HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/request/postWithoutParam");
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            // 处理响应结果
            if (response.getStatusLine().getStatusCode() != 200) {
                log.error("http postWithoutParam error. response:{}", JSON.toJSONString(response));
                return;
            }

            String resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            log.info("http postWithoutParam result:{}", JSON.toJSONString(resultString));
        } catch (Exception e) {
            log.error("http postWithoutParam error", e);
        } finally {
            // 关闭连接
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (Exception e) {
                log.error("http postWithoutParam error", e);
            }
        }
    }

4.2 post 有参

java 复制代码
    public void postWithParam() {
        CloseableHttpResponse response = null;
        // 创建 httpClient 实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建请求实例
        HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/request/postWithParam");
        // 接口请求参数 PostWithParamDto
        PostWithParamDto postWithParamDto = new PostWithParamDto();
        postWithParamDto.setParam("123");
        postWithParamDto.setParam2("456");
        StringEntity entity = new StringEntity(JSON.toJSONString(postWithParamDto), "UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            // 处理响应结果
            if (response.getStatusLine().getStatusCode() != 200) {
                log.error("http postWithParam error. response:{}", JSON.toJSONString(response));
                return;
            }

            String resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            log.info("http postWithParam result:{}", JSON.toJSONString(resultString));
        } catch (Exception e) {
            log.error("http postWithParam error", e);
        } finally {
            // 关闭连接
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (Exception e) {
                log.error("http postWithParam error", e);
            }
        }
    }

    @Data
    public static class PostWithParamDto {
        private String param;
        private String param2;
    }

5 参考文献

(1)HttpClient详细使用示例

相关推荐
田三番11 小时前
使用 vscode 简单配置 ESP32 连接 Wi-Fi 每日定时发送 HTTP 和 HTTPS 请求
单片机·物联网·http·https·嵌入式·esp32·sntp
dulu~dulu11 小时前
查缺补漏----用户上网过程(HTTP,DNS与ARP)
网络·网络协议·http
丶213612 小时前
【网络】HTTP(超文本传输协议)详解
网络·网络协议·http
binqian16 小时前
【k8s】ClusterIP能http访问,但是不能ping 的原因
http·容器·kubernetes
MetaverseMan18 小时前
http防抖和ws防抖
网络·网络协议·http
暂时先用这个名字21 小时前
常见 HTTP 状态码分类和解释及服务端向前端返回响应时的最完整格式
前端·后端·网络协议·http·状态码·国产化·响应
圈圈的熊2 天前
HTTP 和 HTTPS 的区别
前端·网络协议·http·https
这题怎么做?!?2 天前
【Linux】网络编程:实现一个简易的基于HTTP协议格式、TCP传输的服务器,处理HTTP请求并返回HTTP响应;GET方法再理解
linux·服务器·c语言·网络·c++·tcp/ip·http
小兔子酱#2 天前
【Linux 26】应用层协议 - HTTP
linux·运维·服务器·网络·网络协议·http
Amagi.3 天前
HTTP返回码和其含义
网络·网络协议·http