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 entity =newHttpEntity(reqJsonStr,headers);

ResponseEntity 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 entity =newHttpEntity(reqJsonStr,headers);

ResponseEntity resp = restTemplate.exchange(DIC_DATA_URL, HttpMethod.PUT, entity, Map.class);

(3)DELETE请求

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

(4)GET请求

ResponseEntity 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中参数变量值

你可能感兴趣的:(Spring RestTemplate 之exchange方法)