[英]check for 4xx Http Code with native Java
I have some java code which checks a http response.我有一些检查 http 响应的 java 代码。 Now, I would like to check the code against the client error (4xx) family, how can I do that?
现在,我想根据客户端错误 (4xx) 系列检查代码,我该怎么做?
int responseCode = ab.sendGetRequest(href);
The simplest solution would be:最简单的解决方案是:
if (400 <= responseCode && responseCode < 500 ){
//...
}
or a bit nicer in terms of coding conventions but giving readability a big hit:或者在编码约定方面更好一些,但对可读性大有帮助:
if (HttpStatus.SC_BAD_REQUEST <= responseCode &&
responseCode < HttpStatus.SC_INTERNAL_SERVER_ERROR)
How can I check responseCode
against the 4xx
family somehow like the following...如何以某种方式检查
4xx
系列的responseCode
,如下所示...
CLIENT_ERROR.contains(code)
The important point is, that I don't want to use a custom solution (writing my own CLIENT_ERROR
or check against a range,...).重要的一点是,我不想使用自定义解决方案(编写自己的
CLIENT_ERROR
或检查范围,...)。 Isn't there an according Class in java already present for this purpose?为此目的,java中是否已经存在相应的类?
I'm actually utilizing javax.ws.rs.core.Response.Status.Family
now.我现在实际上在使用
javax.ws.rs.core.Response.Status.Family
。 Thank you @Kon for the useful hint!谢谢@Kon 的有用提示!
import javax.ws.rs.core.Response.Status.Family;
if (Family.familyOf(responseCode) == Family.CLIENT_ERROR) {
If using Spring you can simply do :如果使用 Spring,您可以简单地执行以下操作:
HttpStatus.valueOf(statusCode).is4xxClientError()
You can also look at is4xxClientError() implementation if you need anything extra如果您需要任何额外的东西,您还可以查看is4xxClientError()实现
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.