简体   繁体   中英

How can I specify the default MimeType returned by a REST resource with Jersey

I am creating a REST interface and have a resource 'data'. Now I want that an user can specify whether he wants the data as XML or as JSON. Therefore I have created two methods for the same path, one produces application/xml, the other produces application/json. Everything works fine, but how can I specify what should be returned, if an user doesn't set the 'Accept' header field?

My tests have shown that it is not always the same. Yesterday the default was application/xml, today my tests have failed, because as default application/json was returned.

How can I specify a default?

Code Snippet:

@GET
@Path("/rest/data")
@Produces(MediaType.APPLICATION.XML)
public Object getDataAsXML() {
    // return data in XML format
}

@GET
@Path("/rest/data")
@Produces(MediaType.APPLICATION_JSON)
public Object getDataAsJSON() {
    // return data in JSON format
}

Cheers,

metalhamster

@Path("/myResource")
@Produces("text/plain")// doGetAsPlainText method defaults to the MIME type of the @Produces annotation at the class level. 
public class SomeResource {
    @GET
    public String doGetAsPlainText() {
        ...
    }

    @GET
    @Produces("text/html")
    public String doGetAsHtml() {
        ...
    }
}

The doGetAsPlainText method defaults to the MIME type of the @Produces annotation at the class level. The doGetAsHtml method's @Produces annotation overrides the class-level @Produces setting, and specifies that the method can produce HTML rather than plain text.

@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.

@Produce

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM