4

I am using java.net.HttpURLConnection, and it annoyingly presents a window asking for username and password whenever a 401 response code is returned by the HTTP server.

How can I get rid of this automatic auth dialog? I want to handle 401s myself.

I tried setAllowUserInteraction(false), but it seems to have no effect.

Dan Getz
  • 8,774
  • 6
  • 30
  • 64
Dr.Haribo
  • 1,778
  • 1
  • 31
  • 43
  • perhaps this may help - plug in your own Authenticator. http://stackoverflow.com/questions/4883100/how-to-handle-http-authentication-using-httpurlconnection – mdma Aug 29 '11 at 21:50
  • That did the trick! Could you post that as an answer? – Dr.Haribo Aug 30 '11 at 20:12
  • Glad to hear it worked! Answer posted. – mdma Aug 30 '11 at 20:48
  • This happens for me when running under Web Start on both Linux (OpenJDK 7) and Windows (Java 8), but not when running via OpenJDK `java` normally. – Dan Getz Apr 21 '16 at 12:54

2 Answers2

3

The popup comes from the default authenticator. To remove the popup, you can plug in your own authenticator. See How to handle HTTP authentication using HttpURLConnection?

Community
  • 1
  • 1
mdma
  • 56,943
  • 12
  • 94
  • 128
1

@mdma's answer is correct, you can plug in your own Authenticator to handle authentication, so that there's no popup.

If you're already handling authentication in another way (such as by connection.setRequestProperty("Authorization", ...), as this answer to another question describes), you can use Authenticator.setDefault() to choose to not to use any Authenticator for authentication:

Authenticator.setDefault(null);

This removes the old default Authenticator, so that if your authentication is wrong, you get the error response code via your URLConnection, without opening any popup.


An equivalent way is to set the default to an Authenticator which returns null for getPasswordAuthentication() (which is the default implementation), as in the following code:

Authenticator.setDefault(new Authenticator() { });

But unless you're going to add code to your Authenticator, I don't see a reason to choose this over null.

Community
  • 1
  • 1
Dan Getz
  • 8,774
  • 6
  • 30
  • 64