简体   繁体   English

在jax-rs REST服务中更改内容类型

[英]Changing content type in jax-rs REST service

Forgive me, but I may not be familiar with all the lingo necessary to ask this question properly. 请原谅我,但我可能不熟悉正确提出这个问题所需的所有术语。

I'm working on a fairly simple REST web service in Java using the org.apache.cxf.jaxrs.ext implementation of jax-rs. 我正在使用jax-rs的org.apache.cxf.jaxrs.ext实现在Java中开发一个相当简单的REST Web服务。 The method header is like this: 方法标题如下:

@GET
@Path("json/{fullAlias}")
@Produces({"application/json"})
public String json(@PathParam("fullAlias") String fullAlias, @Context MessageContext req)

where MessageContext is org.apache.cxf.jaxrs.ext.MessageContext . 其中MessageContext是org.apache.cxf.jaxrs.ext.MessageContext

There are two things I'm trying to accomplish that I can't seem to figure out: 有两件事我想要完成,我似乎无法弄清楚:

  1. Change the content-type if certain conditions are met (eg for an error) 如果满足某些条件,则更改内容类型(例如,出错)
  2. Change the status code of the response 更改响应的状态代码

I've tried using changing the response by accessing it through the MessageContext: 我试过通过MessageContext访问它来改变响应:

HttpServletResponse response = req.getHttpServletResponse();
response.setContentType("text/plain")
response.setStatus("HttpServletResponse.SC_BAD_REQUEST);

But these changes have no bearing on the response sent; 但这些变化与发送的响应无关; with or without the @Produces annotation, setting the content type inside the method doesn't affect the actual content type (With the annotation, it of course returns "application/json", without it defaults to "text/html"). 无论有没有@Produces注释,在方法内设置内容类型都不会影响实际内容类型(使用注释时,它当然会返回“application / json”,而不会默认为“text / html”)。

I am returning a simple String as the body. 我正在返回一个简单的String作为正文。 I've entertained trying to return a javax.ws.rs.core.Response object to do what I want, but I don't know much about it. 我试图返回一个javax.ws.rs.core.Response对象来做我想做的事,但我不太了解它。

How would I change the content type and/or the status codes from inside this method? 如何从此方法中更改内容类型和/或状态代码?

One approach is to throw a WebApplicationException, as described by Pace, which will work if you are looking to specifically handle an error condition. 一种方法是抛出WebApplicationException,如Pace所描述的,如果您希望专门处理错误条件,它将起作用。 If you are looking to be able to change your content at any time for any reason, then you will want to take a look at returning a Response as the result of your service method rather than a String. 如果您希望能够出于任何原因随时更改您的内容,那么您将需要查看作为服务方法而不是String的结果返回Response。 Returning a Response gives you the greatest amount of control over how your service responds to the client request (it does require more code than returning a simple string). 返回响应可以让您对服务如何响应客户端请求进行最大程度的控制(它需要的代码多于返回简单字符串所需的代码)。

Here is an example of how you would can make use of the Response object: 以下是如何使用Response对象的示例:

@GET
@Path("json/{fullAlias}")
public Response json(@PathParam("fullAlias") String fullAlias, @Context MessageContext req) {
    ...
    if (success) {
        ResponseBuilder rBuild = Response.ok(responseData, MediaType.APPLICATION_JSON);
        return rBuild.build();
    }
    else {
        ResponseBuilder rBuild = Response.status(Response.Status.BAD_REQUEST);
        return rBuild.type(MediaType.TEXT_PLAIN)
                     .entity("error message")
                     .build();
    }    
}

I'm not sure if it's the best approach but I've done the following to solve your question #1. 我不确定这是否是最好的方法,但我已经做了以下工作来解决你的问题#1。

public WebApplicationException createStatusException(String statusMessage) {
    ResponseBuilder rb = Response.noContent();
    rb = rb.type(MediaType.TEXT_PLAIN);
    rb = rb.status(Status.BAD_REQUEST);
    rb = rb.entity(statusMessage);
    return new WebApplicationException(rb.build());
}

EDIT: I then threw the resulting WebApplicationException . 编辑:然后我抛出了生成的WebApplicationException

You can write your own Response Filter to change the content-type header. 您可以编写自己的响应过滤器来更改内容类型标头。

@Provider
public class MimeAddingFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
        responseContext.getHeaders().add("Content-Type", "image/png");
    }

}

This filter will add the "image/png" content-type header. 此过滤器将添加“image / png”内容类型标头。 You can also change or remove headers in JAX-RS response filters. 您还可以在JAX-RS响应过滤器中更改或删除标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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