Reputation: 22972
My service method Produces one of this MediaTypes
it may produce pdf
or excel
file or other.
@Produces({"application/pdf","application/vnd.ms-excel"...
My Question
My service returns response type with application/pdf
always even if it produces excel
. Why?
Than I rearranged MediaTypes
.
@Produces({"application/vnd.ms-excel","application/pdf",...
Now it's giving type application/vnd.ms-excel
for all responses,again Why?
I am using com.sun.jersey
API for client and getting type by the use of
clientResponse.getType()
Probably I think I misunderstood the concept of @Produces
annotation.
Please Clarify.
Following is code of my Service method.
response = Response.ok((Object) file);//file is Object of File
response.header("Content-Disposition","attachment; filename="+filename);
//filename can be a.pdf b.xlsx etc
return response.build();
Upvotes: 4
Views: 6201
Reputation: 34900
As it said in the documenation:
@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
...
}
The doGetAsXmlOrJson method will get invoked if either of the media types "application/xml" and "application/json" are acceptable. If both are equally acceptable then the former will be chosen because it occurs first.
Also, you can use quality factor
for specifying which media type is more preferable:
@Produces({"application/xml; qs=0.9", "application/json"})
.
In any way, if you want to be sure about which media type is used, you should divide your methods into two different signatures.
Upvotes: 5
Reputation: 1600
The @Produces
annotation is used by the JAX-RS implementation to bind the incoming request to one of your Resource Methods, based on the accept
header of the request.
You can set the exact type of the response in the returned Response
object using ResponseBuilder#type(MediaType)
if you want to enforce one media type in particular.
If you want to match the accept
header of the incoming request ("application/vnd.ms-excel" vs "application/pdf" in your case), you can retrieve that header by adding a parameter annotated with @HeaderParam("accept")
in your Java method.
HTH.
Upvotes: 2
Reputation: 97130
JAX-RS methods should base the preferred content type on the value of the Accept
header of your request. Failing that, it should default to the first specified.
While the JAX-RS spec is somewhat vague on the subject, the Jersey documentation is very clear in describing the selection mechanism.
Upvotes: 6