How do I connect to a URL using Basic authentication?
Author: Deron Eriksson
Description: This Java tutorial describes how to connect to a URL using Basic authentication.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


Page:    1 2 >

Connecting to a web site using Basic authentication is fairly straightforward. In another tutorial, we saw that Basic authentication relies on a Base64 encoded 'Authorization' header whose value consists of the word 'Basic' followed by a space followed by the Base64 encoded name:password.

The ApacheSW common codec project at http://commons.apache.org/codec/ contains the Apache standard for Base64 encoding/decoding, so we can add that to a project.

'testing' project

The ConnectToUrlUsingBasicAuthentication class connects to a web page using Basic authentication. It takes a name and a password and concatenates them with a colon in between. It Base64 encodes the resulting string. It makes a URL connection to a web site and sets the 'Authorization' request property to be 'Basic <base-64-encoded-auth-string>' . It reads the content from the URL and displays it to standard output.

ConnectToUrlUsingBasicAuthentication.java

package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

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

public class ConnectToUrlUsingBasicAuthentication {

	public static void main(String[] args) {

		try {
			String webPage = "http://192.168.1.1";
			String name = "admin";
			String password = "admin";

			String authString = name + ":" + password;
			System.out.println("auth string: " + authString);
			byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
			String authStringEnc = new String(authEncBytes);
			System.out.println("Base64 encoded auth string: " + authStringEnc);

			URL url = new URL(webPage);
			URLConnection urlConnection = url.openConnection();
			urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
			InputStream is = urlConnection.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);

			int numCharsRead;
			char[] charArray = new char[1024];
			StringBuffer sb = new StringBuffer();
			while ((numCharsRead = isr.read(charArray)) > 0) {
				sb.append(charArray, 0, numCharsRead);
			}
			String result = sb.toString();

			System.out.println("*** BEGIN ***");
			System.out.println(result);
			System.out.println("*** END ***");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

The execution of the ConnectToUrlUsingBasicAuthentication class is shown below.

Console output

(Continued on page 2)

Page:    1 2 >