使用RestTemplate提交表单数据

用exchange方法提交

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进行提交

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());
相关文章
相关标签/搜索