1. 程式人生 > >Spring Boot rest api 返回 XML 格式的資料

Spring Boot rest api 返回 XML 格式的資料

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 格式的資料 請求資料