Vizible’s Blog

Simple Authentication

Posted in Programming by wearetherock on October 16, 2008
package rss.test.http;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Authenticator;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.Scanner;

public class AuthExample {

    public static void main(String args[]) throws MalformedURLException, IOException {

        Authenticator.setDefault(new MyAuth());

        URL url = new URL("http://twitter.com/statuses/friends_timeline.xml?count=5");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        //connection.setRequestMethod("GET");
        //connection.setDoOutput(true);
        //PrintWriter out = new PrintWriter(connection.getOutputStream());

        //out.println("count=5");

        Scanner s = new Scanner(connection.getInputStream());

        while (s.hasNext()) {

            System.out.println(s.nextLine());
        }
    }
}

class MyAuth extends Authenticator {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {

        char passwd[] = "xxxxxx".toCharArray();
        return new PasswordAuthentication("wearetherock@hotmail.com", passwd);

    }
}

Java Support for HTTP Authentication

J2SE (1.2 and above) provides native support for authentication with the Authenticator class. All you need to do is inherit from it and implement the getPasswordAuthentication method. This method gets a username and password and returns them as a PasswordAuthentication object. Once this is done, you need to register an instance of your authenticator using Authenticator.setDefault. Now, whenever you try to request a protected resource, getPasswordAuthentication will be called. The Authenticator class manages all low-level details, and the good news is that it is not restricted to HTTP, but applies to all network connections.  see : High-Level Network Programming by Qusay H. Mahmoud

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: