Android Volley - HTTP 代码 401 的奇怪错误 - java.io.IOException:未找到身份验证挑战

Android Volley - Strange Error with HTTP code 401- java.io.IOException: No authentication challenges found

我在发送请求并返回代码为 401 的响应时遇到此错误:

com.android.volley.NoConnectionError: java.io.IOException: No authentication challenges found

有人说:
发生此错误是因为服务器发送了 401(未经授权)但未给出 "WWW-Authenticate" 提示客户端下一步该做什么。 "WWW-Authenticate" Header 告诉客户端需要哪种身份验证(基本或摘要)。这在无头 http 客户端中通常不是很有用,但这就是标准的定义方式。发生错误是因为库试图解析 "WWW-Authenticate" header 但不能。 ( android - volley error No authentication challenges found )

但这对我来说很奇怪,因为我不想使用 WWW-authenticate 东西,我只想得到代码 401,但我总是得到异常。

如何绕过这个问题?非常感谢任何建议。

我做了一些研究,得出的结论是,这是一个服务器问题,没有遵循约定。 来自维基:

401 Unauthorized (RFC 7235) Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. See Basic access authentication and Digest access authentication.

我认为解决此问题的最佳方法是在服务器中添加 header(类似于:

WWW-Authenticate: xBasic realm=""

对于我来说,我无法更改服务器,所以我必须检查错误消息以检测 401 错误:

if (error.getMessage().equalsIgnoreCase("java.io.IOException: No authentication challenges found")){
    showLoginError();
}

不是很优雅的解决方案,但现在可以使用。