views:

1557

answers:

4

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();

A: 

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

Peter Štibraný
+3  A: 

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

James Van Huis
+1  A: 

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

José Leal
A: 

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

Pat Gonzalez