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

Using Java to Call RESTful web services

The following code snippet demonstrates how to call a RESTful web service that requires BASIC Authentication:



public static String connectToResource() {

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

try {
URL url = new URL("http://localhost:8080/WEB_APP/RESOURCE/PRODUCT_ID");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Basic " +
new String(com.sun.jersey.core.util.Base64.encode(username + ":" + password)));
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((result = in.readLine()) != null)
status += result;
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return status;
}