Rectangle 27 0

httpurlconnection Connecting to remote URL which requires authentication using Java?


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

@Yura: no. It's got to be global. You can, however, do evil things such as setting a global authenticator which pulls the credentials out of thread-local variables, and set the credentials per thread before making the HTTP connection.

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

How do you handle a bad authentication event? [For example, if the user supplies username and password authentication credentials that don't match anything]?

The above code works but is quite implicit as to whats going on. There's subclassing and method overriding going on there, dig into the docs for those classes if you care to know what's going on. The code here is more explicit javacodegeeks

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

Note
Rectangle 27 0

httpurlconnection Connecting to remote URL which requires authentication using Java?


URL url = new URL(location address);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

Didn't work for me this way... Only the way that @James Van Huis was good

Does not work in general unless you .trim() the result, or call a method variant that does not produce chunked output. javax.xml.bind.DatatypeConverter seems safer.

It's 'native' on Grails and many other Java frameworks because them all use Apache Commons Libs.

The Base64 class can be provided by Apache Commons Codec.

There's a native and less intrusive alternative, which works only for your call.

Note
Rectangle 27 0

httpurlconnection Connecting to remote URL which requires authentication using Java?


URL url = new URL(location address);
URLConnection uc = url.openConnection();

String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

Thanks for the pointer to a 'native' Base64 encoder!

You can also use the following, which does not require using external packages:

Note
Rectangle 27 0

httpurlconnection Connecting to remote URL which requires authentication using Java?


URL url = new URL("http://user:pass@domain.com/url");
URLConnection urlConnection = url.openConnection();

if (url.getUserInfo() != null) {
    String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
    urlConnection.setRequestProperty("Authorization", basicAuth);
}

InputStream inputStream = urlConnection.getInputStream();

Does not work if pass contains a #

If you are using the normal login whilst entering the username and password between the protocol and the domain this is simpler. It also works with and without login.

If your username/password contain special characters, I believe you would need to urlencode those. Then, in the snippet of code above, you would pass url.getUserInfo() thorugh URLDecoder.decode() first (@Peter Rader).

This was exactly what I've been searching for the past 30 minutes. Thanks a lot!

Note
Rectangle 27 0

httpurlconnection Connecting to remote URL which requires authentication using Java?


URL url = new URL("http://user:pass@domain.com/url");
URLConnection urlConnection = url.openConnection();

if (url.getUserInfo() != null) {
    String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
    urlConnection.setRequestProperty("Authorization", basicAuth);
}

InputStream inputStream = urlConnection.getInputStream();

If you are using the normal login whilst entering the username and password between the protocol and the domain this is simpler. It also works with and without login.

This was exactly what I've been searching for the past 30 minutes. Thanks a lot!

Note
Rectangle 27 0

httpurlconnection Connecting to remote URL which requires authentication using Java?


import org.apache.commons.codec.binary.Base64;

HttpGet getRequest = new HttpGet(endpoint);
getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding());

private String getBasicAuthenticationEncoding() {

        String userPassword = username + ":" + password;
        return new String(Base64.encodeBase64(userPassword.getBytes()));
    }

Be really careful with the "Base64().encode()"approach, my team and I got 400 Apache bad request issues because it adds a \r\n at the end of the string generated.

Here is our solution :

Note
Rectangle 27 0

httpurlconnection Connecting to remote URL which requires authentication using Java?


URL url = new URL("http://www.mywebsite.com/resource");
URLConnection urlConnection = url.openConnection();
String header = "Basic " + new String(android.util.Base64.encode("user:pass".getBytes(), android.util.Base64.NO_WRAP));
urlConnection.addRequestProperty("Authorization", header);
// go on setting more request headers, reading the response, etc
  • Use basic java.net.URLConnection and set the Authentication-Header manually like shown here

As i have came here looking for an Android-Java-Answer i am going to do a short summary:

If you want to use java.net.URLConnection with Basic Authentication in Android try this code:

Note
Rectangle 27 0

httpurlconnection Connecting to remote URL which requires authentication using Java?


URL url = new URL(path);
String userPass = "username:password";
String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);//or
//String basicAuth = "Basic " + new String(Base64.encode(userPass.getBytes(), Base64.No_WRAP));
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Authorization", basicAuth);
urlConnection.connect();
Note
Rectangle 27 0

httpurlconnection Connecting to remote URL which requires authentication using Java?


import org.apache.commons.codec.binary.Base64;

HttpGet getRequest = new HttpGet(endpoint);
getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding());

private String getBasicAuthenticationEncoding() {

        String userPassword = username + ":" + password;
        return new String(Base64.encodeBase64(userPassword.getBytes()));
    }

Be really careful with the "Base64().encode()"approach, my team and I got 400 Apache bad request issues because it adds a \r\n at the end of the string generated.

Here is our solution :

Note
Rectangle 27 0

httpurlconnection Connecting to remote URL which requires authentication using Java?


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

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

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

How do you handle a bad authentication event? [For example, if the user supplies username and password authentication credentials that don't match anything]?

The above code works but is quite implicit as to whats going on. There's subclassing and method overriding going on there, dig into the docs for those classes if you care to know what's going on. The code here is more explicit javacodegeeks

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

Note