Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

后端 未结 3 1721
-上瘾入骨i
-上瘾入骨i 2020-12-05 01:51

I am working with Spring 4.0.7

About Spring MVC, for research purposes, I have the following:

@RequestMapping(value=\"/getjsonperson\", 
                    


        
3条回答
  •  佛祖请我去吃肉
    2020-12-05 02:42

    Using Accept header is really easy to get the format json or xml from the REST service.

    This is my Controller, take a look produces section.

    @RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
        public UIProperty getProperties() {
            return uiProperty;
        }
    

    In order to consume the REST service we can use the code below where header can be MediaType.APPLICATION_JSON_VALUE or MediaType.APPLICATION_XML_VALUE

    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", header);
    
    HttpEntity entity = new HttpEntity(headers);
    
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);
    return response.getBody();
    

    Edit 01:

    In order to work with application/xml, add this dependency

    
        com.fasterxml.jackson.dataformat
        jackson-dataformat-xml
    
    

提交回复
热议问题