gpt4 book ai didi

java - Jersey 默认媒体类型(如果不存在 Accept header )

转载 作者:数据小太阳 更新时间:2023-10-29 02:12:16 24 4
gpt4 key购买 nike

在 Jersey 用户指南中,我阅读了以下内容:

@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
...
}

If both are equally acceptable then the former will be chosen because it occurs first.

但是在我的 RESTful 服务中(注意 JSON 媒体类型首先出现):

@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public User getUser(@PathParam("id") int id) {
User user = userDao.getUserById(id);
return user;
}

像这样的请求:curl -v -X GET http://localhost:8080/myapp/users/2,返回一个 XML 响应。如果请求指定像 json 或 xml 这样的 Accept header 就可以了。

编辑:

curl --trace - -X GET http://localhost:8080/myapp/users/2
== Info: Adding handle: conn: 0xc2ad68
== Info: Adding handle: send: 0
== Info: Adding handle: recv: 0
== Info: Curl_addHandleToPipeline: length: 1
== Info: - Conn 0 (0xc2ad68) send_pipe: 1, recv_pipe: 0
== Info: About to connect() to localhost port 8080 (#0)
== Info: Trying 127.0.0.1...
== Info: Connected to localhost (127.0.0.1) port 8080 (#0)
=> Send header, 97 bytes (0x61)
GET /myapp/users/2 HTTP/1.1..User-Agent: curl/7.31.0..Hostlocalhost:8080..Accept: */*....
<= Recv header, 17 bytes (0x11)
HTTP/1.1 200 OK..
== Info: Server Apache-Coyote/1.1 is not blacklisted
<= Recv header, 27 bytes (0x1b)
Server: Apache-Coyote/1.1..
<= Recv header, 31 bytes (0x1f)
Content-Type: application/xml..
<= Recv header, 21 bytes (0x15)
Content-Length:234..
<= Recv header, 37 bytes (0x25)
Date: Sat, 07 Jun 2014 15:26:17GMT..
<= Recv header, 2 bytes (0x2)
..
<= Recv data, 234 bytes (0xea)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><user id="2"><name>JOHN</name><surname>DOE</surname><heigth>172.5</heigth><weigth>70.5</weigth></user>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><user id="2"><name>JOHN</name><surname>DOE</surname><heigth>172.5</heigth><weigth>70.5</weigth></user>
== Info: Connection #0 to host localhost left intact

问题:如果不存在 Accept header (*/*),为什么要像媒体类型一样使用 xml?

提前致谢!

最佳答案

如果一个资源方法通过@Produces 注释支持多种媒体类型,并且客户端接受多个媒体类型(例如,有“Accept: */*”头),Jersey 应该返回第一个列出的。 Jersey 2.x 中有一个错误导致媒体类型的顺序被忽略。请参阅问题 JERSEY-2635 .该问题已得到修复,该修复程序应与 Jersey 2.16 一起发布。

关于java - Jersey 默认媒体类型(如果不存在 Accept header ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24097425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com