广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot 如何使用RestTemplate发送Post请求
  • 286
分享到

SpringBoot 如何使用RestTemplate发送Post请求

2024-04-02 19:04:59 286人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录背景:1、待访问的api2、返回对象3、将发送Post请求的部分封装如下4、UserInfo对象5、在Service层封装将要发送的参数6、在控制器中调用service中的方法,

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;

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;

public class Utils {
    
    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;

@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



@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对象做其他的业务了。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: SpringBoot 如何使用RestTemplate发送Post请求

本文链接: https://www.lsjlt.com/news/133039.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • SpringBoot 如何使用RestTemplate发送Post请求
    目录背景:1、待访问的API2、返回对象3、将发送Post请求的部分封装如下4、UserInfo对象5、在Service层封装将要发送的参数6、在控制器中调用service中的方法,...
    99+
    2022-11-12
  • RestTemplate发送HTTP POST请求使用方法详解
    目录一、postForObject发送JSON格式请求二、postForObject模拟表单数据提交三、url支持占位符语法四、postForEntity()方法五、postForL...
    99+
    2022-11-13
  • jquery如何发送post请求
    本篇内容主要讲解“jquery如何发送post请求”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“jquery如何发送post请求”吧! ...
    99+
    2022-10-19
  • Java 使用 HttpClient 发送 GET请求和 POST请求
    目录概述认证方式基础认证Auth用户名密码认证Bearer Token 认证配置超时生成 RequestConfig设置超时时间概述 日常工作中,我们经常会有发送 HTTP 网络请求...
    99+
    2022-11-12
  • 使用hutool工具发送post请求
     import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONObject; import cn.huto...
    99+
    2023-09-08
    json java 前端
  • 怎么使用Postman发送POST请求
    本篇内容介绍了“怎么使用Postman发送POST请求”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!一、创建一个PHP文件,用于接收POST...
    99+
    2023-07-06
  • java使用RestTemplate封装post请求方式
    目录使用RestTemplate封装post请求RestTemplate使用封装1、SpringBoot使用RestTemplate(使用apache的httpclient)2、使用...
    99+
    2022-11-12
  • 使用HttpURLConnection发送POST请求并携带请求参数
    1、先创建URL对象,指定请求的URL地址。 URL url = new URL("http://example.com/api"); 2、调用URL对象的openConnection()方法创建HttpURLConnection对象。 ...
    99+
    2023-08-31
    java spring intellij-idea spring boot
  • RestTemplate发送HTTP GET请求使用方法详解
    目录前言一、getForObject()方法1.1.以String的方式接受请求结果数据1.2.以POJO对象的方式接受结果数据1.3.以数组的方式接收请求结果1.4.使用占位符号传...
    99+
    2022-11-13
  • vue如何实现发送websocket请求和http post请求
    这篇文章主要介绍vue如何实现发送websocket请求和http post请求,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!先给大家介绍下vue发送websocket请求和http...
    99+
    2022-10-19
  • Vue中怎么使用axios发送post请求
    Vue中怎么使用axios发送post请求,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。vue-resource不再维护之后,我也用起了a...
    99+
    2022-10-19
  • RestTemplate使用Proxy代理作为跳板发送请求
    目录前言一、搭建一个代理服务器二、用于测试的服务端三、代理使用者RestTemplate前言 本文是精讲RestTemplate第10篇,前篇的blog访问地址如下: RestTem...
    99+
    2022-11-13
  • vue cli3 项目中如何使用axios发送post请求
    目录使用axios发送post请求首先需要安装对应的第三方包发送post请求 发送get请求将index.js中再添加如下代码vue使用axios的踩坑记录axios跨域解...
    99+
    2022-11-13
  • PHP发送POST请求失败如何解决
    这篇文章主要讲解了“PHP发送POST请求失败如何解决”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“PHP发送POST请求失败如何解决”吧!PHP发送POST请求失败的解决办法:首先通过“e...
    99+
    2023-06-20
  • php curl如何发送get或者post请求
    这篇文章主要为大家展示了“php curl如何发送get或者post请求”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“php curl如何发送get或者post...
    99+
    2022-10-19
  • 怎么利用Javascript发送GET/POST请求
    这篇文章主要为大家展示了“怎么利用Javascript发送GET/POST请求”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“怎么利用Javascript发送GE...
    99+
    2022-10-19
  • 怎么在linux中使用shell中发送post请求
    本篇文章为大家展示了怎么在linux中使用shell中发送post请求,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。今天在linux中使用curl发送一个post请求时,带有json的数据,在发送时...
    99+
    2023-06-09
  • Java中Https发送POST请求[亲测可用]
    1、直接建一个工具类放入即可 public static JSONObject sendPost(String url,String parame,Map<Strin...
    99+
    2022-11-12
  • vue如何发送请求到springboot程序
    今天小编给大家分享一下vue如何发送请求到springboot程序的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。下面是实现的...
    99+
    2023-07-05
  • vue cli3项目中怎么使用axios发送post请求
    今天小编给大家分享一下vue cli3项目中怎么使用axios发送post请求的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了...
    99+
    2023-06-29
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作