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 testList = new ArrayList();
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
io.springfox
springfox-swagger2
2.2.2
io.springfox
springfox-swagger-ui
2.2.2
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
com.fasterxml.jackson.dataformat
jackson-dataformat-xml
再次走起
浏览器
curl
注意对比不支持xml的截图 request headers ,内容一样本次为xml类型数据
服务器根据accept类型(jq ajax 也会推断下面说),从左到右一次匹配,推断返回内容类型 application/xhtml+xml 第二位匹配
即匹配规则为:最明确的优先匹配。
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格式交互数据
--
有误的地方欢迎指正,交流
参考链接