开发者

How to avoid JVM opening auth window when HttpURLConnection hits 401

I am using java.net.HttpURLConnection, and it annoyingly presen开发者_StackOverflow社区ts 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.


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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜