Sunday, March 27, 2011

Connecting to remote URL which requires authentication using Java

How do I connect to a remote URL in Java which requires authentication. I'm trying to find a way to modify the following code to be able to programatically provide a username/password so it doesn't throw a 401.

URL url = new URL(String.format("http://%s/manager/list", _host + ":8080")); HttpURLConnection connection = (HttpURLConnection)url.openConnection();

From stackoverflow
  • You can use http://user:password@host:8080/... to send username/password in your request.

  • You can set the default authenticator for http requests like this:

    Authenticator.setDefault (new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication ("username", "password".toCharArray());
        }
    });
    

    Also, if you require more flexibility, you can check out the Apache HttpClient, which will give you more authentication options (as well as session support, etc.)

  • Hi there, I don't know if it is a web-site,

    but try using apache-commons httpclient http://hc.apache.org/httpclient-3.x/authentication.html

  • This open source library, http://spnego.sourceforge.net, has a SpnegoHttpURLConnection class that also supports Integrated Windows Authentication via Kerberos tokens.

0 comments:

Post a Comment