srinannapa srinannapa - 1 month ago 8
Java Question

why getPasswordAuthentication() is not being called?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;

import sun.net.www.protocol.http.AuthCacheImpl;
import sun.net.www.protocol.http.AuthCacheValue;



public class RunHttpSpnego {
public static void main(String args[]) throws MalformedURLException,
IOException {
String urlString = "http://www.yahoo.com";
String username = "XXXXXXXXX";
String password = "XXXXXXXX";
// This is modified after the question is being asked. Now this code works fine
System.setProperty("http.proxyHost","176.x.xx.xx") ;
System.setProperty("http.proxyPort", "8080") ;

Authenticator.setDefault(new MyAuthenticator(username, password));


URL url = new URL(urlString);
InputStream content = (InputStream) url.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
System.out.println("Done.");
}

static class MyAuthenticator extends Authenticator {
private String username, password;

public MyAuthenticator(String user, String pass) {
username = user;
password = pass;
}

protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("Requesting Host : " + getRequestingHost());
System.out.println("Requesting Port : " + getRequestingPort());
System.out.println("Requesting Prompt : " + getRequestingPrompt());
System.out.println("Requesting Protocol: "
+ getRequestingProtocol());
System.out.println("Requesting Scheme : " + getRequestingScheme());
System.out.println("Requesting Site : " + getRequestingSite());
return new PasswordAuthentication(username, password.toCharArray());
}
}
}


-- What do i check now , getPasswordAuthentication is not at all being called ? I'm sure my IE is authentication enabled , but not sure what type of authentication was it.

Answer

The Authenticator is only used for websites using basic HTTP authentication (websites wherein you see the well known Javascript-style login/password popup), not websites using form based authentication (a HTML based <form> with login and password fields in usually an eyecandy markup/style) and also not as dialup-like login for your ISP. For the former, you actually need to pass the login as querystring and for the latter, you actually need to manually connect the ISP beforehand or create/use a proxy.