您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“SpringBoot怎么用RestTemplate發(fā)送Post請(qǐng)求”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
背景:
1、待訪問(wèn)的API
2、返回對(duì)象
3、將發(fā)送Post請(qǐng)求的部分封裝如下
4、UserInfo對(duì)象
5、在Service層封裝將要發(fā)送的參數(shù)
6、在控制器中調(diào)用service中的方法,并返回?cái)?shù)據(jù)
7、測(cè)試效果
Spring中有個(gè)RestTemplate類用來(lái)發(fā)送HTTP請(qǐng)求很方便,本文分享一個(gè)SpringBoot發(fā)送POST請(qǐng)求并接收返回?cái)?shù)據(jù)的例子。
用戶信息放在8081端口的應(yīng)用上,8082端口應(yīng)用通過(guò)調(diào)用api,傳遞參數(shù),從8081端口應(yīng)用的數(shù)據(jù)庫(kù)中獲取用戶的信息。
我要訪問(wèn)的api是 localhost:8081/authority/authorize,這個(gè)api需要傳遞三個(gè)參數(shù),分別是domain(域名),account(用戶賬號(hào)),key(用戶秘鑰)。先用postman測(cè)試一下,返回結(jié)果如下:
分別展示了驗(yàn)證成功和驗(yàn)證失敗的例子。
ResultVO類是我構(gòu)造的類,將會(huì)格式化api返回的數(shù)據(jù),實(shí)現(xiàn)如下:
ResultVO.java
package com.seven.site.VO; /** * @author: Seven.wk * @description: 數(shù)據(jù)返回類 * @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; } }
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發(fā)送post請(qǐng)求 * @param url 目的url * @param params 發(fā)送的參數(shù) * @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); //將請(qǐng)求頭部和參數(shù)合成一個(gè)請(qǐng)求 HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); //執(zhí)行HTTP請(qǐng)求,將返回的結(jié)構(gòu)使用ResultVO類格式化 ResponseEntity<ResultVO> response = client.exchange(url, method, requestEntity, ResultVO.class); return response.getBody(); } }
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: 用戶信息實(shí)體 * @create: 2018/07/04 */ @Entity public class UserInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer userId; //用戶標(biāo)識(shí)id private String userName; //用戶姓名 private String userAccount; //用戶賬號(hào) private String userPassword; //用戶密碼 private Date createTime = new Date(System.currentTimeMillis()); //創(chuàng)建時(shí)間 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 + '}'; } }
并調(diào)用該方法,將返回的結(jié)果格式化成UserInfo對(duì)象,其中的異常處理部分就不詳述了。
注:其中的URL地址一定要加上協(xié)議前綴(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); //發(fā)送Post數(shù)據(jù)并返回?cái)?shù)據(jù) ResultVO resultVo = Utils.sendPostRequest(authorizeUrl, params); if(resultVo.getCode() != 20){ //進(jìn)行異常處理 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); }
IndexController.java
/** * 獲取用戶信息 * @param domain 域名 * @param account 用戶輸入的賬號(hào) * @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); }
我們?cè)L問(wèn)該控制器的地址:localhost:8082/site/getInfo,返回結(jié)果如下:
正確返回結(jié)果,測(cè)試成功。
之后我們就可以返回的UserInfo對(duì)象做其他的業(yè)務(wù)了。
“SpringBoot怎么用RestTemplate發(fā)送Post請(qǐng)求”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。