阐述使用 HttpClient 进行 http 请求

1 概述

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

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

(2)Maven 依赖

<dependency><groupId>org.apache.httpcomponents.client5</groupId><artifactId>httpclient5</artifactId><version>5.3</version>
</dependency>

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

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

2 Http接口案例

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

@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();}@Datapublic static class PostWithParamDto {private String param;private String param2;}}

3 get请求

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

3.1 get 无参

    /*** 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 有参

    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 无参

    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 有参

    public void postWithParam() {CloseableHttpResponse response = null;// 创建 httpClient 实例CloseableHttpClient httpClient = HttpClients.createDefault();// 创建请求实例HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/request/postWithParam");// 接口请求参数 PostWithParamDtoPostWithParamDto 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);}}}@Datapublic static class PostWithParamDto {private String param;private String param2;}

5 参考文献

(1)HttpClient详细使用示例

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/819497.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

漂亮,功能就差?错!优秀B端一定是颜值、体验、功能三位一体。

每次发一些漂亮的B端页面&#xff0c;都会有些人跳出来怼&#xff0c;他们都有一个固定的思维模式&#xff1a;漂亮的B端&#xff0c;一定功能差。这就好比马路上看到开豪车的美女&#xff0c;就觉得钱来路不正。 先给大家看一些过气的B端界面&#xff0c;是不是有似曾相识的感…

Java 集合【补充复习】

Java 集合【补充复习】 Java 集合概述Collection 接口继承树Map 接口继承树 Collection 接口方法使用 iterator 接口遍历集合元素使用 forearch 遍历集合元素 List 接口List 实现类之一&#xff1a;ArrayListList 实现类之二&#xff1a;LinkedList Set 接口Set 实现类之一&…

【Alphalens】使用Alphalens配合Akshare进行双均线因子分析,附源码及常见问题

Alphalens 是非常著名的一个python因子分析库。但是该库由于目前已经不怎么维护&#xff0c;问题非常多。最新的使用建议使用alphalens-reloaded&#xff0c;地址&#xff1a;stefan-jansen/alphalens-reloaded: Performance analysis of predictive (alpha) stock factors (gi…

【数据结构|C语言版】顺序表应用

前言1. 基于动态顺序表实现通讯录1.1 通讯录功能1.2 代码实现1.2.1 SeqList.h1.2.2 SeqList.c1.2.3 Contact.h1.2.4 Contact.c1.2.5 test.c 1.3 控制台测试1.3.1 添加联系人1.3.2 删除联系人1.3.3 修改联系人1.3.4 查找联系人1.3.5 清空通讯录1.3.6 通讯录读档和存档 2. 好题测…

Netty 心跳(heartbeat)——服务源码小结(四十三)

ldleStateHandler 可以实现心跳功能&#xff0c;当服务器和客户端没有任何读写交互时&#xff0c;并超过了给定的时间&#xff0c;则会触发用户 handler 的 userEventTriggered 方法。用户可以在这个方法中尝试向对方发送信息&#xff0c;如果发送失败&#xff0c;则关闭连接。…

Java SPI机制详解

Java SPI机制详解 1、什么是SPI&#xff1f; SPI 全称为 (Service Provider Interface) &#xff0c;是JDK内置的一种服务提供发现机制。SPI是一种动态替换发现的机制&#xff0c; 比如有个接口&#xff0c;想运行时动态的给它添加实现&#xff0c;你只需要添加一个实现。我们…

力学笃行(五)Qt QWidgets类

Qt QWidgets类 QDockWidgetQDockWidget与QToolBar&#xff1a;QDockWidget与QMenuBar&#xff1a; QDockWidget QDockWidget属于Qt的窗口部件&#xff08;Widgets&#xff09;模块&#xff0c;这个模块提供了一组用于构建图形用户界面&#xff08;GUI&#xff09;的基本控件和…

Linux下SPI设备驱动实验:SPI设备驱动框架编写

一. 简介 Linux下的SPI 驱动框架和 I2C 很类似&#xff0c;都分为主机控制器驱动和设备驱动&#xff0c;SPI主机控制器是半导体厂商编写的&#xff0c;我们只需要编写 SPI设备驱动代码。 本实验的最终目的就是驱动 I.MX6ULL-ALPHA 开发板上的 ICM-20608 这个 SPI 接口的六轴…

B端:导航条长得不都一样吗?错了,这里看过来就懂了。

B端导航条看似都一样&#xff0c;大差不差&#xff0c;仔细看一下&#xff0c;其实各有各的不同&#xff0c;这里方向了十多个&#xff0c;大家仔细看细节。

avicat连接异常,错误编号2059-authentication plugin…

错误原因为密码方式不对&#xff0c;具体可自行百度 首先管理员执行cmd进入 mysql安装目录 bin下边 我的是C:\Program Files\MySQL\MySQL Server 8.2\bin> 执行 mysql -u -root -p 然后输入密码 123456 进入mysql数据库 use mysql 执行 ALTER USER rootlocalhost IDE…

关于沃进科技无线模块demo软件移植问题

文章目录 一、无线模块开发测试准备二、开发板硬件三、开发板默认功能上电默认界面功能选择界面数据包发送界面数据包接收显示界面射频性能测试界面参数设置界面固件信息显示界面 四、软件开发软件SDK框图1、射频硬件驱动&#xff08;详见./radio/myRadio_gpio.c&#xff09;2、…

51单片机实验04 -数码管的动态显示实验

目录 一、实验目的 二、实验内容 三、实验原理 四、实验方法 五&#xff0c;实验效果及代码 1&#xff0c;效果 2&#xff0c;代码 六&#xff0c;课后习题 1&#xff0c;使用定时器T0的中断函数1 从999999~0计时 1&#xff09;效果 2&#xff09;代码 2&#xff0c…

配置linux的oracle 21c启停服务

一、配置启停 1、使用root用户登陆 su - root 2、修改oratab文件 修改oratab文件&#xff0c;将红框里面的N改为“Y”&#xff0c;使启停脚本能够生效 vi /etc/oratab 3、验证 配置好后就能够使用 dbshut 停止服务 和 dbstart 启动服务 了 2.1启动服务 su - oracle dbstart…

什么是线程?线程和进程谁更弔?

第一个参数是所创建进程的pid。 第二个是线程的属性。 第三个参数是返回值为void*&#xff0c;参数也为void*的函数指针。 第四个参数是给第三个参数的参数&#xff0c;也就是给给函数传参。 #include<iostream> #include<pthread.h> #include<unistd.h>…

折叠面板组件(vue)

代码 <template><div class"collapse-info"><div class"collapse-title"><div class"title-left">{{ title }}</div><div click"changeHide"> <Button size"small" v-if"sho…

生产计划和排单管理怎么做

阅读本文&#xff0c;你将了解到&#xff1a;1、企业是如何制定生产计划和进行排单管理&#xff1f; 2.企业在执行生产计划和进行排单管理过程中会遇到那些问题&#xff1f; 3.企业如何高效利用工具去解决问题&#xff1f; 一、生产计划和排单管理是什么 1.生产计划和排单管理…

【uniapp】【uview2.0】【u-sticky】Sticky 吸顶

把pages.json文件中的 “navigationStyle"设置为"custom”, 出现的问题是&#xff0c;莫名奇妙多了个 一个高度 解决方法 /* 使用CSS的sticky定位 */ .sticky {/* #ifdef H5 */ position: -webkit-sticky;position: sticky;top: 0; /* 设置距顶部的距离 */z-ind…

[Python开发问题] Selenium ERROR: Unable to find a matching set of capabilities

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:「stormsha的主页」…

在Spring Boot实战中碰到的拦截器与过滤器是什么?

在Spring Boot实战中&#xff0c;拦截器&#xff08;Interceptors&#xff09;和过滤器&#xff08;Filters&#xff09;是两个常用的概念&#xff0c;它们用于在应用程序中实现一些通用的逻辑&#xff0c;如日志记录、权限验证、请求参数处理等。虽然它们都可以用于对请求进行…

最大子树和(遇到的题)

题目是给出一个树&#xff0c;求其中最大的权值块 题解&#xff1a; #include <bits/stdc.h> using namespace std; const int N1e59; int dp[N]; //dp[i]表示第i结点为根最大权值 int w[N]; //记录每个结点的权值 int n; //点的数量 int t; //样例个数 …