[英]Custom Response + HTTP status?
我的項目有一個休息界面。 對於一個類,我有一個POST方法,你可以發布一個xml,我返回一個自定義響應,如:
<customResponse>Invalid email</customResponse>
如果發布的xml中的電子郵件不正確+我為不同情況定義的其他自定義消息。
對於所有這些,HTTP STATUS自動置於200(OK)。 有沒有辦法改變它?
Ps:我知道我可以拋出一個Web應用程序:
throw new WebApplicationException(Response.Status.BAD_REQUEST);
但在這種情況下,我的自定義響應不再包括在內。
所以我只想將自定義錯誤+ 400作為http響應返回。
提前致謝。
評論后更新 :我的方法是:
@POST
@Path("{membershipExternalId}")
@Consumes(MediaType.APPLICATION_XML)
@Produces("application/xml")
public CustomResponse invite(){ //code}
你看,我回復了我的CUSTOM RESPONSE。 如果我會返回簡單的響應我可以設置狀態但在這種情況下我看不到任何方式。
找到解決方案:
將返回類型作為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)可以解決問題。 當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>
這是標記的Java,但我不認識Response.Status.BAD_REQUEST。
對於Java,只需在HttpServletResponse對象上調用setStatus即可。
對於.NET,它看起來像這樣:
HttpContext.Current.Response.StatusCode = xxx;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.