4
votes

In Jersey User Guide i read the following:

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

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

However in my RESTful service (note that JSON media type occurs first):

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

A request like: curl -v -X GET http://localhost:8080/myapp/users/2, returns an XML response. If the request specifies Accept header like json or xml all is ok.

EDIT:

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

Question: Why if not Accept header is present (*/*) use xml like media type?

Thanks in advance!

1
can you give use the call trace please using the command : curl --trace - jeorfevre
In my case Jersey browser sends preflight OPTIONS request with "Accept: /" header. And Jersey returns 500 with WADL info... - Azamat Almukhametov
(* Chrome browser) I solved by adding @OPTIONS method returning Ok. Not elegant... - Azamat Almukhametov

1 Answers

2
votes

If a resource method supports multiple media types via @Produces annotation, and the client accepts more than one (e.g. has "Accept: */*" header), Jersey should return the one listed first. There was a bug in Jersey 2.x that caused the order of the media types to be ignored. See issue JERSEY-2635. The issue has been fixed and the fix should be released with Jersey 2.16.