Sunday, 12 August 2012

Java client for invoking a RESTful service

Below is a sample REST Java client written using Apache Commons HttpClient. Though the same can be achieved using java.net classes HttpClient is preferred as it provides higher and more functional  level of abstraction.



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;

import atg.core.util.StringUtils;
import atg.nucleus.GenericService;

/**
 * @author kshabarinath
 * This is a sample REST client which is used to access a service exposed using URL pattern
 *
 */


public static void main(String[] args) {
String requestURL = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/999";
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(requestURL);
String line;
InputStream rstream;
try {
int statusCode = client.executeMethod(method);
String response = getResponseBody(method);
System.out.println("RESPONSE::"+response);
} catch(HttpException e){
e.printStackTrace();

}catch (IOException e) {

// TODO Auto-generated catch block
e.printStackTrace();
}finally{
method.releaseConnection();
}
}



private static String getResponseBody(GetMethod method){
if(method!=null && method.hasBeenUsed()){
BufferedReader in = null;
StringWriter stringOut = new StringWriter();
BufferedWriter dumpOut = new BufferedWriter(stringOut,8192);
try{
in=new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
String line = "";
while((line=in.readLine())!=null){
dumpOut.write(line);
dumpOut.newLine();
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
dumpOut.flush();
dumpOut.close();
if(in!=null){
in.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return stringOut.toString();
}
return null;
}

OUTPUT of the Program


RESPONSE::<?xml version="1.0"?><CUSTOMER xmlns:xlink="http://www.w3.org/1999/xlink">
    <ID>999</ID>
    <FIRSTNAME>Sylvia</FIRSTNAME>
    <LASTNAME>Ott</LASTNAME>
    <STREET>361 College Av.</STREET>
    <CITY>Viena</CITY>
</CUSTOMER>


No comments:

Post a Comment