Thursday, December 8, 2011

Using Java to access a URL through a proxy

The following code snippet demonstrates how to access a URL through a proxy that requires authentication:


public static String connectToProxy() {

String result = "";
String status = "";

Authenticator.setDefault(new ProxyAuthenticator(username, password));
System.setProperty("http.proxyHost", PROXY_HOST);
System.setProperty("http.proxyPort", PROXY_PORT);

try {
URL url;
url = new URL("http://google.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((result = in.readLine()) != null)
status += result;
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return status;
}

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());
}
}

1 comment:

  1. Your blog give many information thanks for share this informative article.
    Files Tube UK proxy

    ReplyDelete