是否可以在 Java 中明确返回 401 Unauthorized 响应代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14393574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:07:51  来源:igfitidea点击:

Is it possible in Java to return the 401 Unauthorized response code explicitly

javaweb-servicessoapauthorization

提问by Patan

I am working on a web service. I want to return the 401: Unauthorizedresponse to the user for invalid credentials.

我正在开发一个网络服务。我想将401: Unauthorized无效凭据的响应返回给用户。

How do I manually return this response code?

如何手动返回此响应代码?

回答by Bogdan Calmac

For error status codes like 401, use the more specific sendError():

对于 401 之类的错误状态代码,请使用更具体的sendError()

httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "your message goes here");

This takes care of everything, it sets the status code and also writes the response.

这会处理所有事情,它设置状态代码并写入响应。

回答by Austin Greco

assuming you are using servlets, you would set the http status to 401 using the setStatusmethod:

假设您正在使用 servlet,您可以使用以下setStatus方法将 http 状态设置为 401 :

httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

HttpServletResponse info

HttpServletResponse 信息

回答by Luis Limas

I've learned the following from both Austin'sand Bodgananswers, this may save some minutes for someone else looking for this answer.

我从AustinBodgan 的答案中了解到以下内容,这可能会为其他寻找此答案的人节省一些时间。

For me, the correct answer is Bodgand's:

对我来说,正确答案是Bodgand 的

httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "your message goes here");

The reason is that responses being thrown using the sendErrormethod are catched by the web.xmlfilters

原因是使用该sendError方法抛出的响应被web.xml过滤器捕获

So if you had specified at your web.xmlfilter this:

因此,如果您在web.xml过滤器中指定了以下内容:

<error-page>
    <error-code>401</error-code>
    <location>/errors/401.jsp</location>
</error-page>

You will only see that error-page when you use the sendErrormethod.

您只会在使用该sendError方法时看到该错误页面。