Vizible’s Blog

Simple Authentication

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


import java.util.Scanner;

public class AuthExample {

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

        Authenticator.setDefault(new MyAuth());

        URL url = new URL("");

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

        //PrintWriter out = new PrintWriter(connection.getOutputStream());


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

        while (s.hasNext()) {


class MyAuth extends Authenticator {

    protected PasswordAuthentication getPasswordAuthentication() {

        char passwd[] = "xxxxxx".toCharArray();
        return new PasswordAuthentication("", 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


Leave a Reply

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

You are commenting using your 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: