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

发布于 2024-08-16 18:55:19 字数 623 浏览 7 评论 0 原文

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

例如,

return Response.status(401).build();

生成一个 HTTP 响应,其中包含:

HTTP/1.1 401 Unauthorized

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

HTTP/1.1 401 Authorization Required

我尝试了以下方法,但没有成功:

1) 这只是将字符串添加到 HTTP 响应的正文中

return Response.status(401).entity("Authorization Required").build();

2 )也有同样的结果:

ResponseBuilder rb = Response.status(401);
rb = rb.tag("Authorization Required");
return rb.build();

感谢您的帮助!

-spd

In Jersey, how can we 'replace' the status string associated with a known status code?

e.g.

return Response.status(401).build();

generates a HTTP response that contains:

HTTP/1.1 401 Unauthorized

I (not me, but the client application) would like to see the response as:

HTTP/1.1 401 Authorization Required

I tried the following approaches but in vain:

1) This just adds the String in the body of the HTTP response

return Response.status(401).entity("Authorization Required").build();

2) Same result with this too:

ResponseBuilder rb = Response.status(401);
rb = rb.tag("Authorization Required");
return rb.build();

Appreciate your help!

-spd

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

后来的我们 2024-08-23 18:55:20

要在 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());
     }

}

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

throw new UnauthorizedException("Authorization Required");

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

Jersey 用户指南中也对此进行了解释 - 尽管代码实际上略有不正确:

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

To do this in Jersey you have the concept of WebApplicationException class. One method is to simply extend this class and all one of the methods to set the error text that is returned. In your case this would be:

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());
     }

}

Now in your code that implements the rest service you would simply throw a new exception of this type, passing in the text value in the constructor e.g.

throw new UnauthorizedException("Authorization Required");

That can create a class like this for each of your web exceptions and throw in a similar fashion.

This is also explained in the Jersey user guide - although the code is actually slightly incorrect:

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

南薇 2024-08-23 18:55:20

我不确定 JSR 339:JAX-RS 2.0:RESTful Web 的 Java API服务是否已经涵盖了这一点。

您可能必须扩展 Response.StatusType 为此。

public abstract class AbstractStatusType implements StatusType {

    public AbstractStatusType(final Family family, final int statusCode,
                              final String reasonPhrase) {
        super();

        this.family = family;
        this.statusCode = statusCode;
        this.reasonPhrase = reasonPhrase;
    }

    protected AbstractStatusType(final Status status,
                                 final String reasonPhrase) {
        this(status.getFamily(), status.getStatusCode(), reasonPhrase);
    }

    @Override
    public Family getFamily() { return family; }

    @Override
    public String getReasonPhrase() { return reasonPhrase; }

    @Override
    public int getStatusCode() { return statusCode; }

    public ResponseBuilder responseBuilder() { return Response.status(this); }

    public Response build() { return responseBuilder().build(); }

    public WebApplicationException except() {
        return new WebApplicationException(build());
    }

    private final Family family;
    private final int statusCode;
    private final String reasonPhrase;
}

这里有一些扩展的状态类型。

public class BadRequest400 extends AbstractStatusType {

    public BadRequest400(final String reasonPhrase) {
        super(Status.BAD_REQUEST, reasonPhrase);
    }
}

public class NotFound404 extends AbstractStatusType {

    public NotFound404(final String reasonPhrase) {
        super(Status.NOT_FOUND, reasonPhrase);
    }
}

我就是这样做的。

@POST
public Response create(final MyEntity entity) {

    throw new BadRequest400("bad ass").except();
}

@GET
public MyEntity read(@QueryParam("id") final long id) {

    throw new NotFound404("ass ignorant").except();
}

// Disclaimer
// I'm not a native English speaker.
// I don't know what 'bad ass' or 'ass ignorant' means.

I'm not sure JSR 339: JAX-RS 2.0: The Java API for RESTful Web Services already covered this or not.

You might have to extend the Response.StatusType for this.

public abstract class AbstractStatusType implements StatusType {

    public AbstractStatusType(final Family family, final int statusCode,
                              final String reasonPhrase) {
        super();

        this.family = family;
        this.statusCode = statusCode;
        this.reasonPhrase = reasonPhrase;
    }

    protected AbstractStatusType(final Status status,
                                 final String reasonPhrase) {
        this(status.getFamily(), status.getStatusCode(), reasonPhrase);
    }

    @Override
    public Family getFamily() { return family; }

    @Override
    public String getReasonPhrase() { return reasonPhrase; }

    @Override
    public int getStatusCode() { return statusCode; }

    public ResponseBuilder responseBuilder() { return Response.status(this); }

    public Response build() { return responseBuilder().build(); }

    public WebApplicationException except() {
        return new WebApplicationException(build());
    }

    private final Family family;
    private final int statusCode;
    private final String reasonPhrase;
}

And here are some extended statust types.

public class BadRequest400 extends AbstractStatusType {

    public BadRequest400(final String reasonPhrase) {
        super(Status.BAD_REQUEST, reasonPhrase);
    }
}

public class NotFound404 extends AbstractStatusType {

    public NotFound404(final String reasonPhrase) {
        super(Status.NOT_FOUND, reasonPhrase);
    }
}

This is how I do.

@POST
public Response create(final MyEntity entity) {

    throw new BadRequest400("bad ass").except();
}

@GET
public MyEntity read(@QueryParam("id") final long id) {

    throw new NotFound404("ass ignorant").except();
}

// Disclaimer
// I'm not a native English speaker.
// I don't know what 'bad ass' or 'ass ignorant' means.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文