Spring RestTemplate中exchange示例大全
下文笔者讲述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中参数变量值
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。