I am using an HttpsUrlConnection
with Basic Authentication by using an Authenticator
and setting a default Authenticator
object like this:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "userpass"
.toCharArray());
}
});
When I access my web-service the connection calls my getPasswordAuthentication()
method to get the credentials and sends this to the web-server. This works allright as long as the password is correct. :)
However, it just happened that someone changed the basic authentication password on the web-server and then my request did not return.
I debugged it and what happens is that my call to getInputStream()
never returns. The HttpsUrlConnection
does get a 401 response and reacts to this internally by getting the same credentials again. But since I only provided one user and password this will fail again (and again...).
So my question is: How can I prevent this and where is there a hook to react to a wrong password (resp. a 401 response) so I can show an appropriate error message and cancel the request?
Here is an extract of the stack trace of the methods that are called repeatingly on HttpsUrlConnection
:
1: MyOwnHttpConnection$3.getPasswordAuthentication() line: 99
2: Authenticator.requestPasswordAuthentication(InetAddress, int, String, String, String) line: 162
3: HttpsURLConnectionImpl$HttpsEngine(HttpURLConnectionImpl).getAuthorizationCredentials(String) line: 1205
4: HttpsURLConnectionImpl$HttpsEngine(HttpURLConnectionImpl).processAuthHeader(String, String) line: 1178
5: HttpsURLConnectionImpl$HttpsEngine(HttpURLConnectionImpl).processResponseHeaders() line: 1118
6: HttpsURLConnectionImpl$HttpsEngine(HttpURLConnectionImpl).retrieveResponse() line: 1044
7: HttpsURLConnectionImpl$HttpsEngine(HttpURLConnectionImpl).getInputStream() line: 523
8: HttpsURLConnectionImpl.getInputStream() line: 283