【问题标题】:Is it possible in Java to return the 401 Unauthorized response code explicitly是否可以在 Java 中显式返回 401 Unauthorized 响应代码
【发布时间】:2013-01-18 06:31:27
【问题描述】:

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

如何手动返回此响应码?

【问题讨论】:

  • 需要更多信息,您使用的是 servlet 还是某些框架?
  • 401错误不是异常,是响应码。
  • @agreco 我想将此作为响应代码发送。我正在使用网络服务。
  • 您使用哪个库来实现 Web 服务?
  • @TechSpellBound。我正在使用 javax.jws.WebService;

标签: java web-services soap authorization


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    HttpServletResponse info

    【讨论】:

      【解决方案3】:

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

      对我来说,正确答案是Bodgand's

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

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

      因此,如果您在 web.xml 指定过滤器:

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

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

      【讨论】:

        猜你喜欢
        • 2023-02-15
        • 1970-01-01
        • 2015-03-13
        • 2021-09-02
        • 2020-02-09
        • 2021-10-11
        • 1970-01-01
        • 2011-05-20
        • 2014-11-13
        相关资源
        最近更新 更多