Dr.Haribo
Dr.Haribo

Reputation: 1778

How to avoid JVM opening auth window when HttpURLConnection hits 401

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.

Upvotes: 4

Views: 1158

Answers (2)

Dan Getz
Dan Getz

Reputation: 9152

@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.

Upvotes: 1

mdma
mdma

Reputation: 57757

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?

Upvotes: 3

Related Questions