SpringBoot使用RestTemplate发送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对象做其他的业务了。

猜你喜欢

转载自blog.csdn.net/zai_xia/article/details/80926157