restTempalte使用

RestTemplate

一、get请求几种方式

不带参数的get请求

ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class);

带查询参数的get亲求 (占位符)

ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/sayhello?name={1}", String.class, "张三");

 Map<String, String> map = new HashMap<>();
 map.put("name", "caoxueqin");
 ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/sayhello?name={name}", String.class, map);

  • 使用UriComponents 进行url拼接, 再采用第一种方式
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParams(params);
restTemplate.getForEntity(builder.toUriString(), responseType);

二、post请求几种方式

参数在body的form-data


HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

MultiValueMap<String, Object> loginJson = new LinkedMultiValueMap<>();
loginJson.add("id", "123");

restTemplate.postForEntity(url, new HttpEntity<>(loginJson, headers), JSONObject.class);

数据可以摊开, 也可以用实体类或map;

2022-02-14-14-47-10-image.png
  1. 如何需要上传文件, 必须使用这种方式;
  2. 所有上传的数据必须摊开, 不能用实体类或者map

参数在body的x-www-from-urlencoded里面

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, Object> loginJson = new LinkedMultiValueMap<>();
loginJson.add("id", "123");

JSONObject jsonObject= restTemplate.postForObject(url,new HttpEntity<>(loginJson,headers),JSONObject.class);

将表单内的数据转换为键值对, post默认的编码格式

eg: param1=11&param2=22

参数在body的raw里面

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

JSONObject jo = new JSONObject();
jo.put("id", "123");

JSONObject jsonObject = restTemplate
                    .postForObject(url,new HttpEntity<>(jo,headers),JSONObject.class);

eg;

{

"param1": 11,

"param2": 22

}

post 请求中 查询参数必须和数据分离开: 查询参数用urlcomponents; 数据必须得用实体类或者map接收(直接把数据写在方法上spring 接收不到);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容