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對象做其他的業務瞭。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: