Spring-boot oauth2使用RestTemplate進行後臺自動登入的實現
阿新 • • 發佈:2020-07-04
內容不限於登入業務,主要簡單介紹RestTemplate的用法,包括
- 使用RestTemplate進行post請求 postForObject
- 使用RestTemplate帶body/form-data進行post請求 MultiValueMap
- 使用RestTemplate帶josn進行post請求JSONObject
- 使用RestTemplate帶頭資訊headers進行post請求 HttpHeaders
登入流程
- 定義 RestTemplate
- 定義 MultiValueMap,構造 post的body內容
- 定義 HttpHeaders,構造請求的頭部資訊
- 定義 HttpEntity,傳送請求的實體
- 定義 RestTemplate,進行請求。返回資料
主要程式碼
// 構造 post的body內容(要post的內容,按需定義) MultiValueMap<String,String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.set("grant_type","password"); paramsMap.set("username","yourname"); paramsMap.set("password","yourpassword"); // 構造頭部資訊(若有需要) HttpHeaders headers = new HttpHeaders(); headers.add("Authorization","Basic xxxxxx你的認證金鑰"); // 設定型別 "application/json;charset=UTF-8" headers.setContentType(MediaType.APPLICATION_JSON); // 構造請求的實體。包含body和headers的內容 HttpEntity<MultiValueMap<String,String>> request = new HttpEntity(paramsMap,headers); // 宣告 restTemplateAuth(用作請求) RestTemplate restTemplateAuth = new RestTemplate(); // 進行請求,並返回資料 String authInfo = restTemplateAuth.postForObject("http://localhost:8089/oauth/token",request,String.class);
使用josn請求的示例程式碼
Posting JSON with postForObject JSONObject personJsonObject = new JSONObject(); personJsonObject.put("id",1); personJsonObject.put("name","John"); HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(),headers); String personResultAsJsonStr = restTemplate.postForObject("url",String.class);
到此這篇關於Spring-boot oauth2使用RestTemplate進行後臺自動登入的實現的文章就介紹到這了,更多相關Spring-boot oauth2 後臺自動登入內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!