简体   繁体   English

自定义响应+ HTTP状态?

[英]Custom Response + HTTP status?

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: 对于一个类,我有一个POST方法,你可以发布一个xml,我返回一个自定义响应,如:

<customResponse>Invalid email</customResponse>

if the email from the xml which was posted, was incorrect + other custom messages i have defined for different situations. 如果发布的xml中的电子邮件不正确+我为不同情况定义的其他自定义消息。

For all of these the HTTP STATUS is automatically put on 200 (OK). 对于所有这些,HTTP STATUS自动置于200(OK)。 Is there any way to change it? 有没有办法改变它?

Ps: I know that i can throw a web application like : Ps:我知道我可以抛出一个Web应用程序:

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. 所以我只想将自定义错误+ 400作为http响应返回。

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. 你看,我回复了我的CUSTOM RESPONSE。 If i would return simple RESPONSE i could set the STATUS but in this case i cannot see any way. 如果我会返回简单的响应我可以设置状态但在这种情况下我看不到任何方式。

Found the solution: 找到解决方案:

Put the return type as Response to the method: 将返回类型作为Response放入方法:

     @POST
     @Path("{membershipExternalId}")
     @Consumes(MediaType.APPLICATION_XML)
     @Produces("application/xml")
     public Response invite(){ //code

     if (fail())
        return Response.status(400).entity(customResponse).build();
}

Response.status(400).entity(customResponse) will do the trick. Response.status(400).entity(customResponse)可以解决问题。 When build() it will convert your custom response xml => 当build()它将转换您的自定义响应xml =>

HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
X-Powered-By: Servlet 2.4; JBoss-4.2.3.GA (build: SVNTag=JBoss_4_2_3_GA date=200807181439)/JBossWeb-2.0
Set-Cookie: JSESSIONID=1C72921619A6B32BC1166B3567A39ADA; Path=/
Content-Type: application/xml
Content-Length: 140
Date: Thu, 18 Mar 2010 12:15:15 GMT
Connection: close

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><customResponse><message>Invalid email</message></customResponse>

HttpServletResponse上的setStatussendError应该可以解决问题。

This is tagged Java but I don't recognize Response.Status.BAD_REQUEST. 这是标记的Java,但我不认识Response.Status.BAD_REQUEST。

For Java just call setStatus on the HttpServletResponse object. 对于Java,只需在HttpServletResponse对象上调用setStatus即可。

For .NET it looks like this: 对于.NET,它看起来像这样:

HttpContext.Current.Response.StatusCode = xxx; HttpContext.Current.Response.StatusCode = xxx;

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

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