Java code to connect through Proxy!

For Normal Java Applications, I have successfully connected through Proxy using the method specified in this link
ProxyAuthentication helper class, Code:


package proxytester;

import java.net.Authenticator;
import java.net.PasswordAuthentication;

class ProxyAuthenticator extends Authenticator {

private String user, password;

public ProxyAuthenticator(String user, String password) {
this.user = user;
this.password = password;
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password.toCharArray());
}

}


Code:

package proxytester;

import java.io.IOException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class Main {

public static void main(String[] args) {
Authenticator.setDefault(new ProxyAuthenticator("YOUR USER NAME", "YOUR PASSWORD"));
System.setProperty("http.proxyHost", "172.16.184.5");
System.setProperty("http.proxyPort", "80");

try {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yahooConnection = yahoo.openConnection();
yahooConnection.connect();

System.out.println("Content: "+yahooConnection.getContentType());
} catch (MalformedURLException e) { // new URL() failed
System.out.println("Exception"+e);

}catch (IOException e) { // openConnection() failed
System.out.println("Exception"+e);
}

System.out.println("ok");
}
}

No comments: