Consuming A Service in Java
Consuming A Service in Java
Service(SOAP and
RESTful) in Java
Cheat Sheet For Consuming Services in Java
This document will provide a user the capability to create an
application to consume a sample web service (Both SOAP and
RESTful) in Java using the following technologies
1> Eclipse IDE
Karan Moodbidri and Amey Gawde
7/25/2013
Prerequisites :
Before we start with the process of consuming web services
Eclipse IDE (Kepler preferred - Can be Downloaded from here - Link )
Click Next
Click Next
Click Finish
Click on Project
Click on New
Click On other
Click Next
Click Finish
Click on Project
Right Click on Java Resources in the Project Tree Structure
Click on New
Click on Class
Select the Same options as given in the Picture
Click on Finish
You will have a java program open in front of you
Go to java resources
Go into src
Check the name of the package other than the package you created
Go into the package
Remember to Check the name of the file with Proxy in the end.
Now import the WS package into your java program
Click Next
Click Next
Click Finish
Click on Project
Right Click on Java Resources in the Project Tree Structure
Click on New
Click on Class
Select the Same options as given in the Picture
Click on Finish
You will have a java program open in front of you
You will need to include the following two packages
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
Follow the code given Below :
Note: The String held by variable apiCall should be the URL to the RESTful Service.
Client client = Client.create();
String apiCall = null;
apiCall = "http://www.exampleRestApi/q=";
WebResource webResource = client.resource(apiCall);
String outputString = webResource.get(String.class);
System.out.println(outputString);
We can Consume a REST based Service without using the Jersey API. I will be providing the
instructions Below.
Click on Finish
Now I would go through the code
First we will create a URL variable to store the URL for the Rest Service.
Example code :
URL
We open a HTTP Connection on that URL. We set the requestMethod to "GET" and we
connect to the Rest Service.
Example Code:
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
We now to have read data from the rest service input stream
Example Code:
BufferedReader bufferReader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
Then we read the data from the stream into s String buffer to printed onto the console.
Example Code:
String str;
StringBuffer stringBuffer = new StringBuffer();
while ((str = bufferReader.readLine()) != null) {
stringBuffer.append(str);
stringBuffer.append("\n");
}
System.out.println(stringBuffer.toString());