SpringBoot使用RestTemplate发送Post请求

精讲RestTemplate-POST请求方法使用详解 前言: 其实POST请求方法和GET请求方法上大同小异,RestTemplate的POST请求也包含两个主要方法: postForObject() postForEntity() 二者的主要区别在于,postForObject()返回值是HTTP协议的响应体。postForEntity()返回的是ResponseEntity,ResponseEntity是对HTTP响应的封装,除了包含响应体,还包含HTTP状态码、contentType、contentLength、Header等信息。 一、post 阅读详情

Spring中有个RestTemplate类用来发送HTTP请求很方便,本文分享一个SpringBoot发送POST请求并接收返回数据的例子。

背景:用户信息放在8081端口的应用上,8082端口应用通过调用api,传递参数,从8081端口应用的数据库中获取用户的信息。

1.待访问的API

我要访问的api是 localhost:8081/authority/authorize,这个api需要传递三个参数,分别是domain(域名),account(用户账号),key(用户秘钥)。先用postman测试一下,返回结果如下:


分别展示了验证成功和验证失败的例子。

2.返回对象

ResultVO类是我构造的类,将会格式化api返回的数据,实现如下:

ResultVO.java

package com.seven.site.VO;

/**
 * @author: Seven.wk
 * @description: 数据返回类
 * @create: 2018/07/04
 */
public class ResultVO<T> {

    private Integer code;

    private String message;

    private T data;

    public ResultVO() {
    }

    public ResultVO(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public ResultVO(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
    
}

3.将发送Post请求的部分封装如下:

Utils.java

package com.seven.site.utils;

import com.seven.site.VO.ResultVO;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


/**
 * @author: Seven.wk
 * @description: 辅助工具类
 * @create: 2018/07/04
 */
public class Utils {

    /**
     * 向目的URL发送post请求
     * @param url       目的url
     * @param params    发送的参数
     * @return  ResultVO
     */
    public static ResultVO sendPostRequest(String url, MultiValueMap<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求,将返回的结构使用ResultVO类格式化
        ResponseEntity<ResultVO> response = client.exchange(url, method, requestEntity, ResultVO.class);

        return response.getBody();
    }

}

4.UserInfo对象

UserInfo.java

package com.seven.site.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;

/**
 * @author: Seven.wk
 * @description: 用户信息实体
 * @create: 2018/07/04
 */
@Entity
public class UserInfo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer userId;         //用户标识id

    private String userName;        //用户姓名

    private String userAccount;         //用户账号

    private String userPassword;        //用户密码

    private Date createTime = new Date(System.currentTimeMillis());     //创建时间

    public UserInfo() {
    }

    public UserInfo(Object userAccount, Object userName) {
    }

    public UserInfo(String userAccount, String userName) {
        this.userName = userName;
        this.userAccount = userAccount;
    }

    public UserInfo(String userAccount, String userName, String userPassword) {
        this.userName = userName;
        this.userAccount = userAccount;
        this.userPassword = userPassword;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAccount() {
        return userAccount;
    }

    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", userAccount='" + userAccount + '\'' +
                ", userPassword='" + userPassword + '\'' +
                ", createTime=" + createTime +
                '}';
    }
}

5.在Service层封装将要发送的参数,并调用该方法,将返回的结果格式化成UserInfo对象,其中的异常处理部分就不详述了。

注:其中的URL地址一定要加上协议前缀(http,https等)

UserInfoServiceImpl.java

public UserInfo getUserInfoFromAuthority(String domain, String account, String key) {

    String authorizeUrl = "http://localhost:8081/authority/authorize";

    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("domain", domain);
    params.add("account", account);
    params.add("key", key);

    //发送Post数据并返回数据
    ResultVO resultVo = Utils.sendPostRequest(authorizeUrl, params);

    if(resultVo.getCode() != 20){       //进行异常处理
        switch (resultVo.getCode()){
            case 17: throw new SiteException(ResultEnum.AUTHORIZE_DOMAIN_NOT_EXIST);
            case 18: throw new SiteException(ResultEnum.AUTHORIZE_USER_NOT_EXIST);
            case 19: throw new SiteException(ResultEnum.AUTHORIZE_USER_INFO_INCORRECT);
            default: throw new SiteException(ResultEnum.SYSTEM_ERROR);
        }
    }
    LinkedHashMap infoMap = (LinkedHashMap) resultVo.getData();
    return new UserInfo((String) infoMap.get("userAccount"), (String) infoMap.get("userName"), key);
}

6.在控制器中调用service中的方法,并返回数据

IndexController.java

/**
 * 获取用户信息
 * @param domain        域名
 * @param account       用户输入的账号
 * @param password      用户输入的密码
 * @return ResultVO
 */
@PostMapping("/getInfo")
@ResponseBody
public ResultVO getInfo(@RequestParam("domain") String domain,
                        @RequestParam("account") String account,
                        @RequestParam("password") String password) {
    UserInfo userInfo;
    try{
        userInfo = userInfoService.getUserInfoFromAuthority(domain, account, password);
    }catch(SiteException e){
        return new ResultVO(e.getCode(), e.getMessage());
    }
    return new ResultVO<>(20, "登录成功", userInfo);
}

7.测试效果

我们访问该控制器的地址:localhost:8082/site/getInfo,返回结果如下:



正确返回结果,测试成功。

之后我们就可以返回的UserInfo对象做其他的业务了。

Springboot使用RestTemplate发送Post请求postForEntity (application/x-www-form-urlencoded) Springboot使用RestTemplate发送Post请求postForEntity[application/x-www-form-urlencoded] 背景思路正文ServiceRestTemplate 使用 postForEntity 请求接口基于xml系列注解解析XML返回值XML的一些基本常识实体类与xml文件对应实体代码参考博客 背景 对接请求为(application/x-www-form-urlencoded),返回XML格式接口。 思路 ServiceRestTemplate 使用 阅读详情

相关推荐

Springboot通过RestTemplate发送post请求并且发送文件数据

由于项目需要与外部接口对接,所以需要使用到restTemplate来发送请求,而存在某一个接口需要接受文件类型数据,这种接口参数一般都是通过form-data来接受的,实际上并不难,但是我在写的时候一直报错,最后发现是项目中配置好的restTemplate中发送post请求会将参数打印出来,而参数中包含文件,使用的是JSONObject.toJSONString(),故一直报错,于是打算写此文章记录一下。

mikumiku5的博客 2105

restTemplate 发送post请求

restTemplate 发送get/post请求 restemplate发送post请求获取阿里云短信验证码向阿里云发送post请求获取短信验证码测试 java.lang.IllegalStateException: No instances available for dfsns.market.alicloudapi.com

dj1955的博客 5万+

CH582低功耗实战:从1.2mA降到5uA,我的蓝牙广播功耗优化笔记

本文详细记录了沁恒CH582蓝牙芯片从1.2mA降至5μA的功耗优化全过程。通过建立基准测试环境、分层排查软件配置与IO状态、精细调优射频参数以及硬件层面的电源管理,实现了极致的低功耗表现。文章还提供了实用的功耗测量方法和典型问题排查指南,为蓝牙设备开发者提供了宝贵的参考经验。

weixin_30368405的博客 572

精讲RestTemplate第4篇-POST请求方法使用详解

本文是精讲RestTemplate第4篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层HTTP客户端类库的切换 精讲RestTemplate第3篇-GET请求使用方法详解 如果您阅读完本文章,觉得对您有帮助,请帮忙点个赞,您的支持是我不竭的创作动力 在上一节为大家介绍了RestTemplate的GET请求的两个方法:getForObject()和getForEntity()。其实POST请求方

字母哥博客 1万+

R语言pls包实战:手把手教你用偏最小二乘(PLS)搞定高维数据回归(附完整代码与数据标准化避坑指南)

本文详细介绍了如何使用R语言的pls包进行偏最小二乘(PLS)回归分析,特别针对高维数据回归问题。通过完整的代码示例和数据标准化避坑指南,帮助读者掌握从数据预处理到模型优化的全流程,解决实际应用中的常见问题。

weixin_42662605的博客 350

IC版图设计之OASIS文件格式详解

OASIS(Open Artwork System Interchange Standard)是继GDSII之后新一代的集成电路版图数据交换标准,由SEMI在2004年正式发布(SEMI标准号:SEMI P39)。高压缩率:相比GDSII可减少3-10倍文件体积扩展性强:支持纳米级工艺的复杂图形描述跨平台兼容:独立于EDA工具和操作系统安全增强:内置校验和与加密支持。

ZZcppc的博客 2440

SpringBoot项目中使用RestTemplate发送GET、POST请求

SpringBoot项目发送GET、POST请求,可以使用RestTemplate来完成,简便好用。 一、初始化RestTemplate @Component public class MyConfig { @Autowired RestTemplateBuilder templateBuilder; @Bean public RestTemplate restTemplate() { return templateBuilder.build();

weixin_44975741的博客 7860

GD32 TLI+IPA实战:5分钟搞定RGB888屏幕显示,并开启2D图形加速

本文详细介绍了如何使用GD32微控制器的TLI和IPA功能快速驱动RGB888屏幕并开启2D图形加速。通过硬件配置、时序设置和显存管理,开发者可以高效实现图形界面渲染,并利用IPA加速器提升性能,适用于嵌入式GUI开发等场景。

weixin_29163797的博客 230

Spring Boot发送GET/POST请求——RestTemplate的基本使用

RestTemplate的基本使用——发送GET/POST请求1. RestTemplateConfig配置类2. RestTemplateTest测试类3. 发送GET请求4. 发送POST请求5. POST发送文件 一般我们的Spring Boot工程都是被请求的一方,但某些情况下我们也需要调用别人的接口以实现逻辑,传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐,而Spring提供了一种简单便捷的模板类来进行操作,这就是Res

weixin_50637551的博客 1万+

【异常】OpenClaw 上下文溢出问题(100% context used 309.9k/200k`)排查与解决

摘要:OpenClaw 运行出现"100% context used 309.9k/200k"报错,表示上下文窗口超出200k Token限制。解决方法包括:1) 重启服务或新建会话清空缓存;2) 修改配置文件提升context_window值;3) 长期优化如限制历史对话轮数、分批处理长文本。该问题通常由输入过长或多轮对话累积导致,需控制单次输入量在阈值内。

奶爸的编程之路,也就一周冷个三天 3235

【2025年华为秋招(AI)-11月19日-第二题(200分)- 终端款型聚类识别】(题目+思路+Java&C++&Python解析+在线测试)

该摘要总结了题目要求、输入输出格式、KMeans算法的实现步骤以及关键点。以下是150字内的摘要: 本文提出基于KMeans算法对终端型号进行聚类的方法。通过包间隔时长、连接持续时长、漫游前后信号强度4个特征,使用欧氏距离度量相似度。算法采用固定初始化策略(前k个样本作为初始质心),经过分配-更新迭代,直至质心移动小于1e-8或达到最大迭代次数。最终输出各簇样本数并按升序排列,解决了终端型号自动分类问题。示例显示该方法能有效识别3-4类终端,并准确统计每类数量。

m0_73659489的博客 141

SpringBoot ——— 使用RestTemplate发送带token的GET和POST请求

最近要在项目中调用别人提供的接口服务,网上大概搜了一下,发现除了传统的httpclient之外,Spring也为我们提供了一个非常方便的HTTP客户端,允许我们调用各种rest服务,包括GET,POST,PUT,DELETE等等。折腾了一下发现还挺好用的,下面贴出RestTemplate发送GET和POST的示例代码。 配置类: package com.test.config; import...

Die Another Day! 2万+

Oracle EBS GL日记账批“选定以过账”状态数据修复

日记账来源:应收账款。用户操作过账以后,自动提交请求“过账:单一分类账”一直运行中,该请求执行5,6个小时甚至10多个小时无法完成,导致“标准管理器”阻塞大量请求待定,“冲突解决管理器”的待定数量不断增加。系统管理员不得不把该请求强制取消,此时,日记账批的状态处于“选定以过账”(GL_JE_BATCHES.STATUS为S),如下图 检查此日记账批有3千多条日记账题头,由于日记账比较多,日记账的科目余额计算需要大量服务器资源和执行时间比较长。

陈显平的专栏-Oracle EBS 3245

springboot中使用RestTemplate发送post请求

springboot中使用RestTemplate发送post请求

wodebokecsdn的博客 1702

路径跟踪 | 图解纯追踪算法Pure Pursuit(附ROS C++/Python/Matlab仿真)

纯追踪算法(Pure Pursuit)参考了人类驾驶行为,其基本思想是在待跟踪路径上设置预瞄点(goal-ahead),通过简单的几何方法驱动机器人跟踪预瞄点直至抵达目标位置.本文详细推导纯追踪算法的理论原理及其变种——自适应纯追踪算法(APP)和规范化纯追踪算法(RPP),并提供ROS C++/Python/Matlab三种仿真实现加深理解

FRIGIDWINTER的博客 8407

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

使用SpringBoot的RestTemplate发送post请求时参数带不上

项目中遇到一个向三方发起请求的数据,不过量不大,就几个方法而已,所以为了方便,我直接用了RestTemplate。 1、配置 @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ return new RestTemplate(factory); } @Bean

二祥的工作历程 2318

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

spring-boot中使用RestTemplate发送post请求

在有@service注解类中,自动装载。

fymsnow的专栏 1441

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Spring boot使用RestTemplate发送Post请求

请求 Map<String, Object> param = new HashMap<>(); Map result = restTemplate.exchange( path, HttpMethod.POST, new HttpEntity<>(param, null), new Parameteriz.

宇晨的博客 420

Springboot使用RestTemplate发送Post请求postForEntity (application/json)的坑

当使用RestTemplate进行http请求时,的确很方便,但是当需要进行post请求时遇到了坑 1POST传递参数 :采用 LinkedMultiValueMap ,不能使用HashMap String url = 'http://posturl'; MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>(); map.add("shopid",".

anita9999的博客 1万+

SpringBoot RestTemplate 发送POST请求

SpringBoot RestTemplate 发送POST请求,封装好的,复制粘贴直接用

cszzl123的博客 2338

springboot使用Map接收请求参数 @RequestBody 使用RestTemplate发送http get和post源码 接口中转相当于反向代理

模拟一个请求 Spring @RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);GET方式无请求体,所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交。 ...

chenhao0568的专栏 1万+

restTemplate.postForObject 发送POST请求

1、引用依赖文档: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven...

i168wintop的博客 1万+

http请求使用 RestTemplate 发送 post 请求传递参数

http使用 RestTemplate 发送 post 请求传递参数 代码参考如下 import com.wondersgroup.yilian.interface_monitor_portallogin.entity.ResponseEntity; import com.alibaba.fastjson.JSONObject; import com.wondersgroup.yilian.int...

zhulaosan的博客 3113

springboot 发送post请求

springboot 发送post请求 import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; public static String sendPOSTRequest(String url, MultiValueMap<String, String> params) { RestTemplate client = new RestTe

whale_ao的博客 1万+
上一篇: Linux目录结构说明
下一篇: Maven打包SpringBoot应用
占位符号
博客等级 码龄10年 75粉丝 53原创
评论 18
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值