How to avoid opening virtual JVM window when HttpURLConnection reaches 401

I use java.net.HttpURLConnection , and it annoyingly presents a window asking for a username and password whenever the HTTP server returns a 401 response code.

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

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

+4
source share
2 answers

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

+2
source

@mdma's answer is correct, you can connect your own Authenticator for authentication so that the popup does not exist.

If you are already handling authentication in a different way (for example, connection.setRequestProperty("Authorization", ...) , as this answer to another question ), you can use Authenticator.setDefault() to not use Authenticator for authentication:

 Authenticator.setDefault(null); 

This removes the old default Authenticator , so if your authentication is incorrect, you get an error response code through URLConnection without opening a popup.


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

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

But if you don’t add the code to your Authenticator , I see no reason to choose it over null .

+1
source

Source: https://habr.com/ru/post/1369573/


All Articles