1. 程式人生 > >Spring RestTemplate 之exchange方法

Spring RestTemplate 之exchange方法

chang media () data 服務 pla str type delet

●exchange方法提供統一的方法模板進行四種請求:POST,PUT,DELETE,GET

(1)POST請求

String reqJsonStr = "{\"code\":\"testCode\", \"group\":\"testGroup\",\"content\":\"testContent\", \"order\":1}";
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new
HttpEntity<String>(reqJsonStr,headers); ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL, HttpMethod.POST, entity, Map.class);

(2)PUT請求

String reqJsonStr = "{\"id\":227,\"code\":\"updateCC\", \"group\":\"UPDATE\",\"content\":\"updateCT\", \"order\":9}";
HttpHeaders headers 
= new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(reqJsonStr,headers); ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL, HttpMethod.PUT, entity, Map.class);

(3)DELETE請求

ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL + "?id={id}", HttpMethod.DELETE, null
, Map.class, 227);

(4)GET請求

ResponseEntity<String> results = restTemplate.exchange(url,HttpMethod.GET, null, String.class, params);
說明:1)url: 請求地址;
     2)method: 請求類型(如:POST,PUT,DELETE,GET);
     3)requestEntity: 請求實體,封裝請求頭,請求內容
     4)responseType: 響應類型,根據服務接口的返回類型決定
     5)uriVariables: url中參數變量值

Spring RestTemplate 之exchange方法