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

package test;


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

public class ConnectToUrlUsingBasicAuthentication {

	public static void main(String[] args) {

		try {
			String webPage = "";
			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 = > 0) {
				sb.append(charArray, 0, numCharsRead);
			String result = sb.toString();

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


The execution of the ConnectToUrlUsingBasicAuthentication class is shown below.

Console output

(Continued on page 2)

Page:    1 2 >