1

用exchange方法提交

exchange既可以执行POST方法,还可以执行GET,所以应用最为广泛

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参数

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

国子监阿创
131 声望8 粉丝

任何一个傻瓜都能写出计算机能理解的程序,而优秀的程序员却能写出别人能读得懂的程序。—— Martin Fowler