目录

HttpClient

HttpClient的主要功能

httpclient使用示例主要步骤

Spring Boot 工程结构

HttpClient实现主要代码:

GET

POST

PUT

Delete


HttpClient

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,方便在日常项目开发中,调用第三方接口数据。

HttpClient的主要功能

实现了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
支持 HTTPS 协议
支持代理服务器(Nginx等)等
支持自动(跳转)转向
环境说明:JDK1.8、SpringBoot(2.2.2)

在pom.xml中引入HttpClient的依赖和SpringBoot的基本依赖配置(web,jpa,fastjson,mysql)。

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version>
</dependency>

httpclient使用示例主要步骤

【步骤】:
1)创建一个httpclient对象,注意以下版本问题说明
HttpClient4.0版本前:
HttpClient httpClient = new DefaultHttpClient();
4.0版本后:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
2)创建一个httpGet对象
HttpGet request = new HttpGet(uri);
3)执行请求调用httpclient的execute(),传入httpGet对象,返回CloseableHttpResponse response = httpClient.execute(request, HttpClientContext.create());
4)取得响应结果并处理
5)关闭HttpClient

注意:主动设置编码,防止响应出现乱码

Spring Boot 工程结构

HttpClient实现主要代码:

GET

  /**GET有参:*/@Autowiredprivate UserServiceImple userServiceImple;@Testpublic void getByUsername(){List<User> users = userServiceImple.findByUserName("王三");System.out.println(JSON.toJSONString(users));}@Testpublic void doGetTestWayOne() {// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Get请求HttpGet httpGet = new HttpGet("http://localhost:8080/user/2");// 响应模型CloseableHttpResponse response = null;try {// 配置信息RequestConfig requestConfig = RequestConfig.custom()// 设置连接超时时间(单位毫秒).setConnectTimeout(5000)// 设置请求超时时间(单位毫秒).setConnectionRequestTimeout(5000)// socket读写超时时间(单位毫秒).setSocketTimeout(5000)// 设置是否允许重定向(默认为true).setRedirectsEnabled(true).build();// 将上面的配置信息 运用到这个Get请求里httpGet.setConfig(requestConfig);// 由客户端执行(发送)Get请求response = httpClient.execute(httpGet);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态为:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度为:" + responseEntity.getContentLength());//主动设置编码,防止相应出现乱码System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}}

POST

  /*** POST---有参测试(对象参数)** @date*/@Testpublic void dopostHaveObjectParam() {// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Post请求HttpPost httpPost = new HttpPost("http://localhost:8080/user");User user = new User();user.setUserName("张山");user.setPassword("Ss@1234");// 我这里利用阿里的fastjson,将Object转换为json字符串;// (需要导入com.alibaba.fastjson.JSON包)String jsonString = JSON.toJSONString(user);//  主动设置编码,防止出现乱码StringEntity entity = new StringEntity(jsonString, "UTF-8");// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中httpPost.setEntity(entity);httpPost.setHeader("Content-Type", "application/json;charset=utf8");// 响应模型CloseableHttpResponse response = null;try {// 由客户端执行(发送)Post请求response = httpClient.execute(httpPost);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态为:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度为:" + responseEntity.getContentLength());//主动设置编码,防止相应出现乱码System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}}

PUT

  /*** Put---有参测试(对象参数)** @date*/@Testpublic void doPutObjectParam() {// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Put请求HttpPost httpPut = new HttpPost("http://localhost:8080/user");User user = new User();user.setId((long) 2);user.setUserName("张山");user.setPassword("Ss@1234");// 我这里利用阿里的fastjson,将Object转换为json字符串;// (需要导入com.alibaba.fastjson.JSON包)String jsonString = JSON.toJSONString(user);//  主动设置编码,防止出现乱码StringEntity entity = new StringEntity(jsonString, "UTF-8");// post请求是将参数放在请求体里面传过去的;这里将entity放入Put请求体中httpPut.setEntity(entity);httpPut.setHeader("Content-Type", "application/json;charset=utf8");// 响应模型CloseableHttpResponse response = null;try {// 由客户端执行(发送)Put请求response = httpClient.execute(httpPut);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态为:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度为:" + responseEntity.getContentLength());//主动设置编码,防止相应出现乱码System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}}

Delete

  /*** DeleteTest*/@Testpublic void doDeleteTest() {// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Delete请求HttpDelete httpDelete = new HttpDelete("http://localhost:8080/user/41");// 响应模型CloseableHttpResponse response = null;try {// 配置信息RequestConfig requestConfig = RequestConfig.custom()// 设置连接超时时间(单位毫秒).setConnectTimeout(5000)// 设置请求超时时间(单位毫秒).setConnectionRequestTimeout(5000)// socket读写超时时间(单位毫秒).setSocketTimeout(5000)// 设置是否允许重定向(默认为true).setRedirectsEnabled(true).build();// 将上面的配置信息 运用到这个Delete请求里httpDelete.setConfig(requestConfig);// 由客户端执行(发送)Delete请求response = httpClient.execute(httpDelete);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态为:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度为:" + responseEntity.getContentLength());//主动设置编码,防止相应出现乱码System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}}

HttpClient实现 get、post、put、delete请求相关推荐

  1. 使用HttpClient 发送 GET、POST、PUT、Delete请求及文件上传

    httpclient4.3.6 下进行的测试 package org.caeit.cloud.dev.util; import java.io.File; import java.io.IOExcep ...

  2. Reject: HTTP ‘DELETE‘ is not allowed, Not injecting HSTS.....DELETE请求PUT请求跨域问题

    CORS(DELETE请求.PUT请求) Reject: HTTP 'DELETE' is not allowed [DEBUG] 2021-08-25 15:23:52.401 [http-nio- ...

  3. Golang gin框架:发送GET POST PUT DELETE请求

    package mainimport ("net/http""github.com/gin-gonic/gin" )func main() {r := gin. ...

  4. Tornado的同步API写法举例实现GET/POST/DELETE请求+Tornado获取post请求中的json数据(转载)

    下面的实验主要来自[1][2],但是对实验2的代码进行了修改,修改过程参考了[3] #---------------------------------------------------实验1--- ...

  5. Spring RestTemplate中几种常见的请求方式GET请求 POST请求 PUT请求 DELETE请求

    Spring RestTemplate中几种常见的请求方式 原文地址: https://blog.csdn.net/u012702547/article/details/77917939 版权声明:本 ...

  6. springboot接收浏览器发送delete请求( method not allowed 405解决方法)

    [README] 浏览器使用form提交信息的时候只支持GET和POST,如果需要在浏览器上使用PUT和DELETE请求方式的话,只能使用欺骗的方式了,SpringMvc提供了HiddenHttpMe ...

  7. (转)【SpringMvc】如何使用form发送PUT和DELETE请求

    转自:   https://blog.csdn.net/cockroach02/article/details/82194126https://blog.csdn.net/cockroach02/ar ...

  8. axios.delete()请求方式(含代码)- 应用篇

    axios.delete() 请求的应用 - 代码篇 代码如下: axios.delete(this.serverPath+'/auth/logout', {params: {// 'username ...

  9. SpringBoot2.1.5 (10)--- Http接口之POST,PUT,DELETE 请求

    SpringBoot2.1.5 (10)--- Http接口之POST,PUT,DELETE 请求 POST:向服务器提交数据.这个方法用途广泛,几乎目前所有的提交操作都是靠这个完成. PUT:这个方 ...

最新文章

  1. Java 高级算法——数组中查询重复的数字
  2. 7.22 校内模拟赛
  3. mysql事务隔离级别与锁_mysql事务隔离级别与锁
  4. 除了HTML+CSS,成就高薪web前端还需要学习什么技术?
  5. Vue之安装Google开发插件
  6. E-MapReduce 2.0.0 版本发布
  7. 第二章 Jsp基本语法
  8. 反病毒工具-LordPE
  9. 下载地址url中带有中文是url转换方法
  10. python创建智能问答机器人
  11. 【机器学习算法笔记】5. 自组织映射SOM
  12. CSDN去广告,超清爽界面
  13. 106短信发送失败的原因
  14. 看守所里的信息化故事:刘所家的新地毯
  15. 二维空间内,如何判断两条线段是否相交,相离,平行,重合,并求交点
  16. 2022年数学类保研经验整理(信息与计算科学、计算数学、计算机)
  17. 几大数学软件各有什么优缺点?
  18. 武汉新华电脑学校计算机协会,第十一届大学生计算机应用能力与信息素养大赛·武汉新华颁奖典礼圆满落幕!...
  19. 单个象棋棋子图片!png
  20. 硬件科普系列之硬盘——前言与准备知识篇

热门文章

  1. 将系统盘迁移到固态硬盘,无须重装系统
  2. java sql语句逗号_Java 实现对Sql语句解析
  3. 垂直线在html中怎么做,在html页面的右侧和左侧添加两条垂直线(矩形)
  4. 心田花开:影响孩子注意力的原因大揭秘!
  5. 实时帧数手机_使命召唤手游高帧率帧数多少帧-高帧率帧数介绍_使命召唤手游...
  6. Unreal5 第三人称射击游戏 角色基础制作2
  7. 毛哥的快乐生活(连载至第30篇)
  8. FreeRTOS临界段
  9. 供配电系统之功率的运算
  10. crontab的定时操作