post请求
userData.put("accountid", "-1");
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
headers.add("Content-Type", contentType);
//userData 是请求体body
HttpEntity<Object> entity = new HttpEntity<>(userData, headers);
ResponseEntity resp = HttpUtil.restTemplate.exchange(请求url, HttpMethod.POST, entity, Object.class);
- content-type:application/x-www-form-urlencoded
MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
postParameters.put("param1", Collections.singletonList(param1));
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
headers.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
HttpEntity<Object> entity = new HttpEntity<>(postParameters, headers);
ResponseEntity responseEntity = HttpUtil.restTemplate.exchange(hangupUrl, HttpMethod.POST, entity, Object.class);
- postForEntity、postForObject、postForLocation同getForEntity。
get请求
//第一种
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://uri?name={1}", String.class, "张三");
//第二种
Map<String, String> map = new HashMap<>();
map.put("name", "李四");
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://uri?name={name}", String.class, map);
//第三种
UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://uri?name={name}").build().expand("王五").encode();
URI uri = uriComponents.toUri();
ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
- getForObject同getForEntity
put请求
restTemplate.put("http://uri/{1}", book, 99);
delete请求
restTemplate.delete("http://uri/{1}", 100);