
使用Accept标头真的很容易从REST服务中获取json或xml格式。
这是我的控制器,看一下产生部分。
@RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET) public UIProperty getProperties() { return uiProperty; }为了使用REST服务,我们可以使用下面的代码,其中标头可以是MediaType.APPLICATION_JSON_VALUE或MediaType.APPLICATION_XML_VALUE
HttpHeaders headers = new HttpHeaders();headers.add("Accept", header);HttpEntity entity = new HttpEntity(headers);RestTemplate restTemplate = new RestTemplate();ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);return response.getBody();编辑01:
为了配合使用
application/xml,请添加此依赖项
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId></dependency>
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)