具有多部分/混合响应的HTTP状态代码201

时间:2012-01-19 16:28:17

标签: rest jboss resteasy

我正在尝试创建一个定义为:

的REST服务
@POST
@Path("/path")
@Consumes(MediaType.APPLICATION_XML)
@Produces("multipart/mixed")
public MultipartOutput create(MyObject o) {}

输出的第一部分是XML,第二部分是文本文件。在XML中我有我需要的状态代码,但是如何使用它来创建HTTP状态代码?目前我收到200,我需要201。

(对于其他服务,没有MultipartOutput,响应是使用ResponseBuilder创建的。)

1 个答案:

答案 0 :(得分:0)

<击> 您可以使用@Context访问HttpServletResponse

尝试更改方法签名并致电setStatus

public MultipartOutput create(MyObject o, @Context HttpServletResponse response) {
    MultipartOutput mpo = ...
    response.setStatus(201);

    return mpo;
}

<击>

编辑:

尝试使用org.jboss.resteasy.spi.HttpResponse代替PostProcessInterceptor

import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
import org.junit.Assert;
import org.junit.Test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlRootElement;

public class MultipartTest {
    @XmlRootElement(name = "MyObject")
    static class MyObject {}

    @Path("/")
    public static class Service {
        @Context HttpResponse response;

        @GET
        @Path("/mpo")
        public MultipartOutput create() {
            response.setStatus(201);

            final MultipartOutput mpo = new MultipartOutput();
            mpo.addPart(new MyObject(), MediaType.APPLICATION_XML_TYPE);

            return mpo;
        }
    }

    public static class Interceptor implements PostProcessInterceptor {
        @Context HttpResponse response;

        @Override
        public void postProcess(ServerResponse serverResponse) {
            serverResponse.setStatus(response.getStatus());
        }
    }

    @Test
    public void test() throws Exception {
        Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
        dispatcher.getRegistry().addSingletonResource(new Service());
        dispatcher.getProviderFactory().getServerPostProcessInterceptorRegistry().register(new Interceptor());

        MockHttpRequest request = MockHttpRequest.get("/mpo");
        MockHttpResponse response = new MockHttpResponse();

        dispatcher.invoke(request, response);

        Assert.assertEquals(201, response.getStatus());
    }
}