其他分享
首页 > 其他分享> > Spring RestTemplate 之exchange方法

Spring RestTemplate 之exchange方法

作者:互联网

exchange方法提供统一的方法模板进行四种请求:POST,PUT,DELETE,GET

1、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);

2、PUT请求

String reqJsonStr = "{\"id\":227,\"code\":\"updateCC\", \"group\":\"UPDATE\",\"content\":\"updateCT\", \"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);

3、DELETE请求

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

4、GET请求

ResponseEntity<String> results = restTemplate.exchange(url,HttpMethod.GET, null, String.class, params);

说明:1)url: 请求地址;
     2)method: 请求类型(如:POST,PUT,DELETE,GET);
     3)requestEntity: 请求实体,封装请求头,请求内容
     4)responseType: 响应类型,根据服务接口的返回类型决定
     5)uriVariables: url中参数变量值

标签:HttpMethod,HttpEntity,请求,exchange,Spring,RestTemplate,entity,headers
来源: https://www.cnblogs.com/qianxiaoPro/p/16218166.html