自定义响应HTTP 状态?
我的项目有一个休息界面。 对于一个类,我有一个 POST 方法,您可以在其中发布 xml,然后我返回一个自定义响应,例如:
(
如果电子邮件来自发布的 xml 不正确+我为不同情况定义的其他自定义消息。
对于所有这些,HTTP 状态会自动设置为 200(正常)。 有什么办法可以改变吗?
Ps:我知道我可以抛出一个网络应用程序,例如:
throw new WebApplicationException(Response.Status.BAD_REQUEST);
但在这种情况下,我的自定义响应不再包含在内。
所以我只想返回我的自定义错误 + 400 作为 http 响应。
提前致谢。
评论后更新: 我的方法是:
@POST
@Path("{membershipExternalId}")
@Consumes(MediaType.APPLICATION_XML)
@Produces("application/xml")
public CustomResponse invite(){ //code}
你看到我返回了我的自定义响应。如果我返回简单的响应,我可以设置状态,但在这种情况下我看不到任何方法。
I have a rest interface for my project.
For one class i have a POST method where you can post an xml and i RETURN a custom response like:
<customResponse>Invalid email</customResponse>
if the email from the xml which was posted, was incorrect + other custom messages i have defined for different situations.
For all of these the HTTP STATUS is automatically put on 200 (OK).
Is there any way to change it?
Ps: I know that i can throw a web application like :
throw new WebApplicationException(Response.Status.BAD_REQUEST);
but in this case my custom response is no more included.
So i just want to return my custom error + 400 as http response.
Thanks in advance.
UPDATE after comments:
My method is:
@POST
@Path("{membershipExternalId}")
@Consumes(MediaType.APPLICATION_XML)
@Produces("application/xml")
public CustomResponse invite(){ //code}
You see that i return my CUSTOM RESPONSE. If i would return simple RESPONSE i could set the STATUS but in this case i cannot see any way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
找到解决方案:
将返回类型作为方法的响应:
Response.status(400).entity(customResponse) 就可以了。当 build() 时,它将转换您的自定义响应 xml =>
Found the solution:
Put the return type as Response to the method:
Response.status(400).entity(customResponse) will do the trick. When build() it will convert your custom response xml =>
setStatus< /code>
或
HttpServletResponse
上的sendError
应该可以解决问题。setStatus
orsendError
onHttpServletResponse
should do the trick.这是标记为 Java 的,但我无法识别 Response.Status.BAD_REQUEST。
对于 Java,只需在 HttpServletResponse 对象上调用 setStatus 即可。
对于 .NET,它看起来像这样:
HttpContext.Current.Response.StatusCode = xxx;
This is tagged Java but I don't recognize Response.Status.BAD_REQUEST.
For Java just call setStatus on the HttpServletResponse object.
For .NET it looks like this:
HttpContext.Current.Response.StatusCode = xxx;