JAX/Jersey Custom error code in Response(响应中的 JAX/Jersey 自定义错误代码)
问题描述
在泽西岛,我们如何替换"与已知状态代码相关的状态字符串?
In Jersey, how can we 'replace' the status string associated with a known status code?
例如
return Response.status(401).build();
生成包含以下内容的 HTTP 响应:
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) 这只是在 HTTP 响应的正文中添加字符串
1) This just adds the String in the body of the HTTP response
return Response.status(401).entity("Authorization Required").build();
2) 同样的结果:
ResponseBuilder rb = Response.status(401);
rb = rb.tag("Authorization Required");
return rb.build();
感谢您的帮助!
-spd
推荐答案
要在 Jersey 中执行此操作,您需要使用 WebApplicationException 类的概念.一种方法是简单地扩展此类和所有一种方法来设置返回的错误文本.在您的情况下,这将是:
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());
}
}
现在,在实现 rest 服务的代码中,您只需抛出这种类型的新异常,在构造函数中传递文本值,例如
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.
这在 Jersey 用户指南中也有解释 - 尽管代码实际上略有错误:
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
这篇关于响应中的 JAX/Jersey 自定义错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:响应中的 JAX/Jersey 自定义错误代码
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01