api接口写好了?想过(Accept,Content-Type)?返回类型json|xml?

mac2022-07-05  15

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> 再次走起 浏览器

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/45174399406 http://www.ruanyifeng.com/blog/2014/05/restful_api.htmlHttp报头Accept与Content-Type的区别 http://www.cnblogs.com/-lzb/articles/5035629.html推荐优先使用json https://www.cnblogs.com/jaxu/p/7908111.html#a_1jQ ajax dataType https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings

转载于:https://www.cnblogs.com/dayou123123/p/8298917.html

最新回复(0)