响应中的JAX/Jersey自定义错误代码

23 java http response jersey

在Jersey中,我们如何"替换"与已知状态代码关联的状态字符串?

例如

return Response.status(401).build();
Run Code Online (Sandbox Code Playgroud)

生成包含以下内容的HTTP响应:

HTTP/1.1 401 Unauthorized
Run Code Online (Sandbox Code Playgroud)

我(不是我,但客户端应用程序)希望将响应视为:

HTTP/1.1 401 Authorization Required
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法,但徒劳无功:

1)这只是在HTTP响应的主体中添加了String

return Response.status(401).entity("Authorization Required").build();
Run Code Online (Sandbox Code Playgroud)

2)同样的结果:

ResponseBuilder rb = Response.status(401);
rb = rb.tag("Authorization Required");
return rb.build();
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助!

-spd

jal*_*lch 38

要在Jersey中执行此操作,您将拥有WebApplicationException类的概念.一种方法是简单地扩展此类和所有方法以设置返回的错误文本.在你的情况下,这将是:

import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.*;


public class UnauthorizedException extends WebApplicationException {

    /**
      * Create a HTTP 401 (Unauthorized) exception.
     */
     public UnauthorizedException() {
         super(Response.status(Status.UNAUTHORIZED).build());
     }

     /**
      * Create a HTTP 404 (Not Found) exception.
      * @param message the String that is the entity of the 404 response.
      */
     public UnauthorizedException(String message) {
         super(Response.status(Status.UNAUTHORIZED).entity(message).type("text/plain").build());
     }

}
Run Code Online (Sandbox Code Playgroud)

现在在实现其余服务的代码中,您只需抛出此类型的新异常,在构造函数中传入文本值,例如

throw new UnauthorizedException("Authorization Required");
Run Code Online (Sandbox Code Playgroud)

这可以为每个Web异常创建一个这样的类,并以类似的方式抛出.

这在Jersey用户指南中也有解释 - 虽然代码实际上有点不正确:

https://jersey.github.io/nonav/documentation/latest/user-guide.html/#d4e435