gpt4 book ai didi

httpresponse - 休息轻松响应状态+正文

转载 作者:行者123 更新时间:2023-12-04 03:03:21 28 4
gpt4 key购买 nike

我在休息服务中有以下方法:

    @POST
@Path("/create")
@ResponseStatus(HttpStatus.CREATED)
@Consumes(MediaType.WILDCARD)
public String create( .... ) {.... return json;}

所以我想在正文和状态码已创建时获得带有 json 的响应。

问题是:我无法获得已创建状态的响应。

状态代码总是可以的,所以似乎“@ResponseStatus(HttpStatus.CREATED)”被忽略了......

有人可以帮我吗?

我正在使用休眠 4.1、spring 3.1 和 resteasy 2.3

最佳答案

据我所知,无法通过使用 @org.springframework.web.bind.annotation.ResponseStatus 注释方法来实现此目的。 .

您可以返回javax.ws.rs.core.Response从你的方法:

return Response
.status(Response.Status.CREATED)
.entity("ok")
.build();

或者你可以有 org.jboss.resteasy.spi.HttpResponse注入(inject),直接设置状态码。

可能有更多方法可以做到这一点,但我只知道这两种。

工作测试用例:
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.spi.HttpResponse;
import org.jboss.resteasy.spi.NotFoundException;
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.Response;

public class ResponseTest {


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

@GET
@Path("/1")
public Response createdUsingResponse() throws NotFoundException {
return Response
.status(Response.Status.CREATED)
.entity("ok")
.build();
}

@GET
@Path("/2")
public String created() throws NotFoundException {
response.setStatus(Response.Status.CREATED.getStatusCode());
return "ok";
}
}

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

@Override
public void postProcess(ServerResponse response) {
if(this.response.getStatus() != 0){
response.setStatus(this.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("/1");
MockHttpResponse response = new MockHttpResponse();

dispatcher.invoke(request, response);

Assert.assertEquals(201, response.getStatus());
}
{
MockHttpRequest request = MockHttpRequest.get("/2");
MockHttpResponse response = new MockHttpResponse();

dispatcher.invoke(request, response);

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

关于httpresponse - 休息轻松响应状态+正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12040564/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com