RestTemplate中的三種請求方式postForObject、postForEntity、exchange
阿新 • • 發佈:2018-12-22
public static void main(String[] args) {
RestTemplate template = new RestTemplate();
String url = "http://127.0.0.1:12813/member/c2/f02";
// 封裝引數,千萬不要替換為Map與HashMap,否則引數無法傳遞
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("dt" , "{\"uscInfo\":{\"member\":\"123\",\"isEncrypt\":0,\"tenant\":\"456\",\"devciceIp\":\"789\",\"devciceId\":\"147\"},\"quInfo\":{\"account\":\"258\",\"pushId\":\"369\",\"optSys\":\"159\",\"code\":\"357\",\"addressProvince\":\"153\",\"addressRegion\":\"183\",\"businessType\":\"486\",\"addressCity\":\"759\",\"codeKey\":\"726\"} }" );
postForObject(template, paramMap, url);
postForEntity(template, paramMap, url);
exchange(template, paramMap, url);
}
public static String postForObject(RestTemplate template,MultiValueMap<String, Object> paramMap,String url){
// 1、使用postForObject請求介面
String result = template.postForObject(url, paramMap, String.class);
System.out.println("result1==================" + result);
return result;
}
public static String postForEntity(RestTemplate template,MultiValueMap<String, Object> paramMap,String url){
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
System.out.println("result2====================" + response2.getBody());
return response2.getBody();
}
public static String exchange(RestTemplate template,MultiValueMap<String, Object> paramMap,String url) {
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
ResponseEntity<String> response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class);
System.out.println("result3====================" + response3.getBody());
return response3.getBody();
}