Java HTTP client example with basic authentication 

Joined:
04/09/2007
Posts:
753

March 28, 2011 20:51:30    Last update: March 28, 2011 20:53:46
HTTP basic authentication is just Base64 encoded user name and password passed in as the Authorization header. So the following code works:
// encode user name and password
String credential = org.apache.commons.codec.binary.Base64.encodeBase64String(
                               (username + ":" + password).getBytes()
                    );

// pass encoded user name and password as header
URL url = new URL (urlString);
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + credential);


However, since JDK 1.2, there's a more Java friendly way:
Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
	return new PasswordAuthentication("username", "password".toCharArray());
    }
});


Test code:
import java.net.*;
import java.io.*;

public class JavaURLBasicAuth {
    public static void main(String[] args) throws Exception {
	if (args.length < 3) {
	    System.out.println("Usage: java JavaURLAuth <URL> <UserName> <Password>");
	    return;
	}

        String url = args[0];
        String username = args[1];
        String password = args[2];

	// set default authenticator
	Authenticator.setDefault(new Authenticator() {
	    protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(username, password.toCharArray());
	    }
	});

        // get URL
	URL url = new URL(url);
	URLConnection conn = url.openConnection();
	BufferedReader r = new BufferedReader(
				new InputStreamReader(
				    conn.getInputStream()
				)
			    );
	String line = r.readLine();
	while (line != null) {
	    System.out.println(line);
	    line = r.readLine();
	}
    }
}
Share |
| Comment  | Tags