Thursday, December 8, 2011

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

No comments:

Post a Comment