1. 程式人生 > >RestTemplate提交表單

RestTemplate提交表單

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);