1. 場景描述
現在越來越的系統之間的交互采用http+json的交互方式,以前用的比較多的HttpClient,后來用的RestTemplate,感覺RestTemplate要比httpClent簡潔的多,簡單介紹下,項目中正在使用的get和post調用方式。
2. 解決方案
2.1 簡要說明
RestTemplate是集成在spring-web中的,因為springboot的starter已經默認加載進來,所以可以直接使用不用再配置maven的gav了。
2.2 post調用方式
2.2.1 真實代碼
public static String invoke(String url, HashMap params) throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(params), headers);
RestTemplate rst = new RestTemplate();
ResponseEntity<String> stringResponseEntity = rst.postForEntity(url, httpEntity, String.class);
return stringResponseEntity.getBody();
}
2.2.2 代碼說明
invoke是通用方法調用,項目中的入參是:url和map,url是調用地址,寫在配置文件中;map是外圍系統需要的參數,在相關類中進行封裝后傳過來。
2.3 get調用方式
2.3.1真實代碼
public JSONArray getUsers() throws Exception {
JSONArray result = new JSONArray();
try {
RestTemplate restTemplate = new RestTemplate();
result = restTemplate.getForObject(apiUrl + "/user/list?appCode={1}",
JSONArray.class, code);
} catch (Exception e) {
}
return result;
}
2.3.2 代碼說明
其中參數是:url和code,根據code去查詢對應集合。
2.4 RestTemplate Api說明
DELETE | delete |
GET | getForObject |
getForEntity | |
HEAD | headForHeaders |
OPTIONS | optionsForAllow |
POST | postForLocation |
postForObject | |
postForEntity | |
PUT | put |
any | exchange |
execute |
一般只需記住get與post的五個就可以了(getForObject 、getForEntity、postForLocation、postForObjec、postForEntity),這幾個方法有很多重載的方法,參數不一樣,可根據實際情況調用。