起因:
- A,
B.A调用B提供的api接口. - A: 为毛你的接口返回的是xml格式的 (浏览器访问) ? 给个json行不行 ? -B: 没问题啊,
我们自己的程序一直在用
测试
1. 测试 demo
新建一个 spring boot RESTful API 项目
浏览器地址栏访问, 返回结果没问题, json 数据
@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;
}
默认是不支持 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>
浏览器
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 格式交互数据
--
有误的地方欢迎指正, 交流
参考链接
匹配规则 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
来源: https://www.cnblogs.com/dayou123123/p/8298917.html