exchange既能夠執行POST方法,還能夠執行GET,因此應用最爲普遍,使用方法以下:java
String url = "http://localhost/mirana-ee/app/login"; RestTemplate client = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); // 請勿輕易改變此提交方式,大部分的狀況下,提交方式都是表單提交 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // 封裝參數,千萬不要替換爲Map與HashMap,不然參數沒法傳遞 MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>(); // 也支持中文 params.add("username", "用戶名"); params.add("password", "123456"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers); // 執行HTTP請求 ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class); // 輸出結果 System.out.println(response.getBody());
postForEntity是對exchange的簡化,僅僅只須要減小HttpMethod.POST參數,以下:web
// 上面的代碼徹底同樣 // 僅需替換exchange方法 ResponseEntity<String> response = client.postForEntity(url, requestEntity , String.class );
在Controller的方法參數中,若是將「@ModelAttribute」改成「@RequestBody」註解,則此時的提交方式爲Payload方式提交,詳細的差別請參見《 $.ajax使用總結(一):Form提交與Payload提交》,代碼示例以下:ajax
// 請注意@RequestBody註解 @RequestMapping(value="/login", method=RequestMethod.POST, consumes="application/json") // 千萬不要多此一舉添加@ModelAttribute,不然會被其覆蓋,以下 // public Account getAccount(@RequestBody@ModelAttribute Account account) public Account getAccount(@RequestBody Account account) { account.setVersion(new Date()); return account; }
再次強調一次,千萬不要多此一舉再次添加「@ModelAttribute」,由於其優先級比較高,因此係統會採用表單方式解析提交內容。spring
對於Payload方式,提交的內容必定要是String,且Header要設置爲「application/json」,示例以下:json
// 請求地址 String url = "http://localhost/mirana-ee/app/login"; RestTemplate client = new RestTemplate(); // 必定要設置header HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); // 將提交的數據轉換爲String // 最好經過bean注入的方式獲取ObjectMapper ObjectMapper mapper = new ObjectMapper(); Map<String, String> params= Maps.newHashMap(); params.put("username", "國米"); params.put("password", "123456"); String value = mapper.writeValueAsString(params); HttpEntity<String> requestEntity = new HttpEntity<String>(value, headers); // 執行HTTP請求 ResponseEntity<String> response = client.postForEntity(url, requestEntity , String.class ); System.out.println(response.getBody());
若是內容不是以String方式提交,那麼必定會出現如下錯誤:app
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 400 Bad Request at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63) at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613) at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:407)
最後須要強調的是,經過@RequestBody是沒法獲取到請求參數,如將上面服務端的代碼改成以下格式,則確定得不到數據,但表單提交則相反。post
@RequestMapping(value="/login", consumes="application/json", method=RequestMethod.POST) public Account getAccount(@RequestBody Account account, HttpServletRequest request) { // 確定得不到參數值 System.out.println(request.getParameter("username")); account.setVersion(new Date()); return account; }
在RestTemplate的使用中,HttpEntity用於傳遞具體的參數值,而uriVariables則用於格式化Http地址,而不是地址參數,正確的用法以下:url
入格式化參數path String url = "http://localhost/mirana-ee/app/{path}"; // 準備格式化參數 Map<String, String> varParams = Maps.newHashMap(); varParams.put("path", "login"); // 其餘代碼略 // 格式化提交地址 ResponseEntity<String> response = client.postForEntity(url, requestEntity , String.class, varParams);
在網上的不少例子中,我發現不少人爲了處理Payload提交,都添加了自定義的HttpMessageConverter,以下:調試
// 徹底沒有必要 client.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); client.getMessageConverters().add(new StringHttpMessageConverter());
而後,通過我查看源碼與調試發現,RestTemplate內置了7種HttpMessageConverter,以下:code
org.springframework.http.converter.ByteArrayHttpMessageConverter org.springframework.http.converter.StringHttpMessageConverter org.springframework.http.converter.ResourceHttpMessageConverter org.springframework.http.converter.xml.SourceHttpMessageConverter org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
RestTemplate能大幅簡化了提交表單數據的難度,而且附帶了自動轉換JSON數據的功能,但只有理解了HttpEntity的組成結構(header與body),且理解了與uriVariables之間的差別,才能真正掌握其用法。