devxlogo

HTTP Authorization

HTTP Authorization

Question:
I am writing an application that uses the URLConnection class to open a connection to a web site. However one of the sites I wish to access has web server access control enabled. If I am going through a browser I see a dialog box requiring a username and password. How can I provide this information to the server throught my application. I have seen some information regarding setRequestProperty() which sounds likely enough. Do I have to encode the username/password?Thanks for your help

Answer:
Many programmers like to use Java to automate access to networkresources because it is so easy to write networking code with theJava networking classes. Accessing URL’s through Java is as simpleas creating a URLConnection class instance and fetching its inputstream. However, not all URL’s are publicly accessible and requireauthentication. If you look at the specification for HTTP, you willfind that URL’s requiring a username and password require anAuthorization property to accompany the GET request. The formatfor the Authorization property is the concatenation of the usernameand password separated by a colon and then Base64 encoded.

How do we do this in Java? The URLConnection class has a method calledsetRequestProperty() which can be used to set the value of an HTTPrequest property. The only trick remaining is to Base64 encode theusername and password. There are three ways to do this. You can writeyour own Base64 encoder, you can use a third-party Base64 encoder, oryou can use an undocumented and unsupported class in the Sun JDK. I’llshow you how to do it with the third method. But keep in mind that Sunmakes no guarantees that classes in any of the sun.* packages will be present in future versions of their JDK. In Java 1.2 there willbe a java.net.Authenticator class to make this task easier.

import java.io.*;import java.net.*;import sun.misc.BASE64Encoder;public final class HTTPAuthorization {  public static final void main(String[] args) {    String address, username, password, key;    BASE64Encoder encoder;    URL url;    URLConnection connection;    BufferedReader input;    address  = args[0];    username = args[1];    password = args[2];    key = username + ":" + password;    encoder = new BASE64Encoder();    key = encoder.encode(key.getBytes());    try {      url = new URL(address);      connection = url.openConnection();      connection.setRequestProperty("Authorization", "Basic " + key);      input = new BufferedReader(new InputStreamReader(				       connection.getInputStream()));      while((address = input.readLine()) != null)	System.out.println(address);    } catch(IOException e) {      e.printStackTrace();    }  }}

devx-admin

Share the Post: