exchange既能夠執行POST方法,還能夠執行GET,因此應用最爲普遍java
String url = "http://localhost/"; RestTemplate restTemplate = 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 = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); //輸出結果 System.out.println(response.getBody());
postForEntity是對exchange的簡化,僅僅只須要減小HttpMethod.POST參數post
String url = "http://localhost/"; RestTemplate restTemplate = 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); //僅需替換exchange方法 ResponseEntity<String> response = client.postForEntity(url, requestEntity , String.class); //輸出結果 System.out.println(response.getBody());