Spring RestTemplate中exchange示例大全

戚薇 Spring 发布时间:2023-05-15 17:42:26 阅读数:9052 1
下文笔者讲述RestTemplate中POST,PUT,DELETE,GET的示例分享,如下所示

POST请求

String reqJsonStr = "{\"code\":\"testCode\", \"group\":\"testGroup\",\"content\":\"testContent\", \"order\":1}";
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(reqJsonStr,headers);
ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL, HttpMethod.POST, entity, Map.class);

PUT请求

 
String reqJsonStr = "{\"id\":888,\"code\":\"showInfo",\"content\":\"Info", \"order\":9}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(reqJsonStr,headers);
ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL, HttpMethod.PUT, entity, Map.class);

DELETE请求


ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL + "?id={id}", HttpMethod.DELETE, null, Map.class, 888);

GET请求

ResponseEntity<String> results = restTemplate.exchange(url,HttpMethod.GET, null, String.class, params);
参数说明:
   url:请求地址;
   method:请求类型(如:POST,PUT,DELETE,GET);
   requestEntity:请求实体,封装请求头,请求内容
   responseType:响应类型,根据服务接口的返回类型决定
   uriVariables:url中参数变量值
  
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/Spring/202305/6447.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者