I am using an HttpsUrlConnection
with Basic Authentication by using an Authenticator
and setting a default Authenticator
object like t
I solved this problem by abstracting request/response logic away into a MyRequest
class. This allows me to have a request-scoped variable that can tell my Authenticator
whether it should make a request using a specified username and password, or whether it should stop retrying (by returning null
). It looks somewhat like the following (consider this pseudocode)
public class MyRequest
{
private boolean alreadyTriedAuthenticating = false;
private URL url;
...
public void send()
{
HttpUrlConnection connection = (HttpUrlConnection) url.openConnection();
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
if (!alreadyTriedAuthenticating)
{
alreadyTriedAuthenticating = true;
return new PasswordAuthentication(username, password.toCharArray());
}
else
{
return null;
}
}
InputStream in = new BufferedInputStream(connection.getInputStream());
...
}
}