Spring Boot rest api 返回 XML 格式的数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/github_38151745/article/details/83381098

Spring Boot 默认返回json 格式的数据,Rest Api 可以根据用户请求头的不同 ,返回不同的媒体类型的响应(JSON XML 等)在默认的情况下,Spring 会安装应用所定义的内容协商策略解析正确的内容 (用户可以根据指定 Accept 头信息来返回不同类型的信息) 当我们需要返回xml格式的数据的时候,我们需要使用以下方式来实现

REST 返回XML 格式数据的实现

  1. 在需要返回的bean 上面使用@XmlRootElement (name="") 这个name 代表这个xml 根节点的名称
@XmlRootElement(name = "user")
public class User {
    private String name;
    private int age;
    }

2.在controller 中 对需要返回的接口的requsetMapper ()中添加 produces属性 并使其等于 不同的媒体类型(application/json;charset=UTF-8 或者 application/xml;charset=UTF-8)

@RequestMapping(value = "userInfo", method = RequestMethod.GET, produces = {"application/xml;charset=UTF-8"})
    @ResponseBody
    public ResponseEntity userInfoXml() {
        User user = new User();
        user.setName("sean");
        user.setAge(22);
        return new ResponseEntity(user, HttpStatus.OK);
    }
    @RequestMapping(value = "userInfo", method = RequestMethod.GET ,produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ResponseEntity userInfo() {
        User user = new User();
        user.setName("sean");
        user.setAge(22);
        return new ResponseEntity(user, HttpStatus.OK);
    }

根据请求头Accept 来访问 不同格式的Rest API 数据

当需要请求XML 格式数据的Rest API 的时候,只需要配置请求头 在请求头中添加Accept 并将value 设置为application/xml ,这样在请求的时候就会返回XML 数据,如果不设置的化,默认请求json 格式的数据
请求数据
github url:springbootrestswagger

猜你喜欢

转载自blog.csdn.net/github_38151745/article/details/83381098