JAX-RS请求特定媒体类型

时间:2014-02-03 09:09:57

标签: java rest

假设我有以下REST方法:

@GET
@Path("get/{id}")
@Produces({"application/json", "application/xml"})
public Entity getEntity(@PathParam("id") int id) {
    //do stuff
    Entity entity = find(id);
    return entity;
}

默认情况下,当我使用任何浏览器访问其余端点时,我会返回XML。有没有办法可以在请求中指定我想要返回的媒体类型?或者我必须以某种方式将这些信息包含在路径中吗?

3 个答案:

答案 0 :(得分:1)

除了Content-Type标题之外,您还必须使用所需的媒体类型指定Accept标头,该标头指出请求的内容类型。

因此请使用Accept标头而不是Content-Type标头:

Accept: application/xml

答案 1 :(得分:0)

您应该手动准备回复。例如,如果您需要JSON答案,则应将Entity类转换为Json并返回String。 您可以使用https://code.google.com/p/google-gson/进行转换。

事实上,准备答案是您的决定和工作。唯一需要考虑的是Rest在HTTP之上工作,因此某种文本(JSON,XML,纯文本)是最“友好”的信息格式。

答案 2 :(得分:0)

可能是这个例子可以帮助

<强> RestClientWithAcceptHeader

RestClient client = new RestClient();
    ClientResponse response = client.resource("http://example.com/resources/resource1").header("Accept", "application/json;q=1.0, application/xml;q=0.8").get();
    // find what format was sent back
    String contentType = response.getHeaders().getFirst("Content-Type");

    if (contentType.contains("application/json")) {
        JSONObject entity = response.getEntity(JSONObject.class); /* or use a String, InputStream, or other provider that supports the entity media type */
    } else if (contentType.contains("application/xml") {
        String entity = response.getEntity(String.class); /* or use a JAXB class, InputStream, etc. */

更多herehere