api接口寫好了?想過(Accept,Content-Type)?返回類型json|xml?
起因:
- A,B. A調用B提供的api接口.
- A:為毛你的接口返回的是xml格式的(瀏覽器訪問)?給個json行不行?
- B:沒問題啊,我們自己的程序一直在用
測試
1. 測試demo
- 新建一個spring boot RESTful API項目
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public User index() {
List<String> testList = new ArrayList<String>();
testList.add("aa");
testList.add("bb");
User user=new User();
user.setName("Grace");
user.setTestList(testList);
return user;
}
- 瀏覽器地址欄訪問,返回結果沒問題,json數據
- 默認是不支持xml的,請求頭類型application/xml 無返回數據
2.更直觀點看,spirng boot 集成swagger2 並設置 Response Content Type 支持xml,json類型
- pom
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
- produces
//默認為 */*
//支持xml,json 設置 produces = "application/xml,application/json")
@ApiOperation(value = "user", notes = "note", produces = "application/xml,application/json")
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public User index() {
- 走起
- 注意 Accept,Content-Type , swagger 選擇Response Content Type 受影響的是 request headers
- 當設置xml類型時 拿不到數據,狀態碼406
406 Not Acceptable - [GET]:用戶請求的格式不可得(比如用戶請求JSON格式,但是只有XML格式)。
3. 配置 spring boot RESTful API 支持xml
- pom
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
- 再次走起
- 瀏覽器
2. curl
2. 注意對比不支持xml的截圖 request headers ,內容一樣本次為xml類型數據
3. 服務器根據accept類型(jq ajax 也會推斷下面說),從左到右一次匹配,推斷返回內容類型 application/xhtml+xml 第二位匹配
4. 即匹配規則為:最明確的優先匹配。
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
- swagger 走一波
4. 再來看下jQ 下ajax的情況
- 走起
-
默認情況(不支持xml)
-
配置支持xml
-
$.get(xx,xx,xx,dataType) dataType 默認的情況(*/*),按api文檔說的jQ會智能推斷
總結下
- 瀏覽器
- 在瀏覽器地址欄訪問的情況下
request header Accept:text/html, application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
- 規則,從左到右依次匹配,推斷返回內容類型.最明確的優先匹配.本文中xml,json 都支持下,優先選擇xml
- jQ ajax ,
- 默認情況下
request header accept:*/*
jQ會智能推斷.如上來看json優先級較高 - 通過
dataType
設置request header accept
類型
- 開發層面的建議
- 涉及到跨組,跨部門,前后端分離的情況借用swagger媒介來溝通api接口情況
- 如有xml,json多格式支持的話,設置swagger Response Content Type 來達到多類型支持
- 優先使用json格式交互數據
--
- 有誤的地方歡迎指正,交流
參考鏈接
- 匹配規則 http://blog.csdn.net/blueheart20/article/details/45174399
- 406 http://www.ruanyifeng.com/blog/2014/05/restful_api.html
- Http報頭Accept與Content-Type的區別 http://www.cnblogs.com/-lzb/articles/5035629.html
- 推薦優先使用json https://www.cnblogs.com/jaxu/p/7908111.html#a_1
- jQ ajax dataType https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings