Tuesday, 1 April 2014

Rest client java using apache http client

This blog explains how a rest web service can be called using Apache Http Client API.

Below class is a utility class that transforms a Java object to XML and also the other way around.
This class uses JAXB to marshal an unmarshal the objects and xml string.



import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JAXBUtil {

 public static  String marshall(T object) {
  JAXBContext context;
  try {
   context = JAXBContext.newInstance(object.getClass());
  
  Marshaller marshaller = context.createMarshaller();
  marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
  
  
  StringWriter stringWriter = new StringWriter();
  marshaller.marshal(object, stringWriter);
  return stringWriter.toString();
  } 
  catch (JAXBException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return null;
  }
  
 }
 
 public  static Object   unMarshall(String string, Class bindingObject){
  JAXBContext context;
  Object object = null;
  try {
   context = JAXBContext.newInstance(bindingObject);
   Unmarshaller unmarshaller = context.createUnmarshaller();
   StringReader reader = new StringReader(string);
    object =unmarshaller.unmarshal(reader);
  }catch(Exception e){
   e.printStackTrace();
  }
  return object;
  
 }

}

This class simulates a HTTP request and submits POST request with the XML in he body of the request.

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class MyClass {
 public static void main(String[] args) {
  System.out.println("hi");
  
  Login login = new Login();
  login.setUsername("admin");
  login.setPassword("admin");
  
  String marshalledString = JAXBUtil.marshall(login);
  System.out.println(marshalledString);
  
try {
   
   DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient =new DefaultHttpClient(httpClient.getParams());
            
   // Created Post method with url
   HttpPost postRequest = new HttpPost("http://localhost:8080/rest-web-app/rest/login");
   
   InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(marshalledString.getBytes()), -1);
   reqEntity.setContentType("application/xml");
   reqEntity.setChunked(true);
   postRequest.setEntity(reqEntity);

   System.out.println("Executing request " + postRequest.getRequestLine());

   // submit request
   HttpResponse response = httpClient.execute(postRequest);

   // Read response
   if (response.getStatusLine().getStatusCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
   }
   BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
   String output;
   
   String completeoutput="";
   while ((output = br.readLine()) != null) {
    
    completeoutput += output;
   }

   // close connection
   httpClient.getConnectionManager().shutdown();
   System.out.println(completeoutput);

  }
  catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } 
 }

}

he output received from the HTTP request is printed below

hi
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<login>
    <username>admin</username>
    <password>admin</password>
</login>


<?xml version="1.0" encoding="UTF-8" standalone="yes"?><response><message>login successful</message></response>



For Web Service Introduction click here

Below are some posts that explain how to implement and test SOAP/REST Webservices

Host
SOAP REST
JAX-WS JAX-RS
Spring-ws Spring-MVC-REST
Client
SOAP REST
JAX-WS(wsimport) Google REST APP
SOAP UI Apache REST

Share the post