Tuesday 25 November 2014

Pass java object as HTTP post data


In GET request, parameters are sent as part of URL. In POST request parameters are sent as body of the request (after headers). Below are the step by step details to post a java object to an URL and get the response as an object.

Let’s say I had employee database which stores all my employee details. I want to retrieve employee details based on their ids. I want to send employee id list as post body, and get the response as list of employees.

Step 1: Define Employee class first.
import java.io.Serializable;

public class Employee implements Serializable{
    private String id;
    private String firstName;
    private String lastName;

    Employee(String id, String firstName, String lastName){
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getId() {
        return id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}


Step 2: Write a servlet application, which reads request object (in this case list of employee ids) and send response object (in this case list of employee objects).
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import javax.servlet.ServletOutputStream;

public class GetEmployeeData extends HttpServlet {

    static final Map<String, Employee> empMap = new HashMap<String, Employee> ();

    static{
        empMap.put("E512345", new Employee("E512345", "Hari", "Krishna"));
        empMap.put("E512346", new Employee("E512346", "Joel", "Chinna"));
        empMap.put("E512347", new Employee("E512347", "Surendra", "Sami"));
        empMap.put("E512348", new Employee("E512348", "Praneeth", "Sai"));
        empMap.put("E512349", new Employee("E512349", "Gopi", "Battu"));
        empMap.put("E512350", new Employee("E512350", "Rama", "Krishna"));
        empMap.put("E512351", new Employee("E512351", "Murali", "Krishna"));
        empMap.put("E512352", new Employee("E512352", "Anand", "Bandaru"));
        empMap.put("E512353", new Employee("E512353", "HariPrasad", "Nalasani"));
        empMap.put("E512354", new Employee("E512354", "Murugesh", "Chinnam"));
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res){

        ServletInputStream in = null;
        ObjectInputStream inStream = null;
        ServletOutputStream out = null;
        ObjectOutputStream outStream = null;
        
        try{
            in = req.getInputStream();
            inStream = new ObjectInputStream(in);

            List<String> empId = (List<String>)inStream.readObject();

            List<Employee> empList = new ArrayList<Employee> ();

            Iterator<String> iter = empId.iterator();
            while(iter.hasNext()){
                empList.add(empMap.get(iter.next()));
            }

            out = res.getOutputStream();
            outStream = new ObjectOutputStream(out);
            outStream.writeObject(empList);
            outStream.flush();
        }
        catch(Exception e){
            
        }
        finally{
            try {
                in.close();
                out.close();
                inStream.close();
                outStream.close();
            }
            catch (IOException ex) {
               
            }
        }
    }
   
}


in = req.getInputStream();
Above statement opens request input stream.

inStream = new ObjectInputStream(in);
Creates an ObjectInputStream that reads from the specified InputStream.

List<String> empId = (List<String>)inStream.readObject();
Read an object from the ObjectInputStream and cast it as list of string.

out = res.getOutputStream();
Gets output stream associated with this response.

outStream = new ObjectOutputStream(out);
Creates an ObjectOutputStream that writes to the specified OutputStream.

outStream.writeObject(empList);
Write the specified object to the ObjectOutputStream.
 
Step 3: Write Application class which sends list of employee ids to above servlet as post data, and read the response object send by above servlet.
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class GetEmployeeDetails {
    public static void main(String args[]){
        List<String> empList = new ArrayList<String> ();
        empList.add("E512345");
        empList.add("E512350");
        empList.add("E512352");
        empList.add("E512354");
        empList.add("E512345");

        try{
            URL url = new URL("http://localhost:8080/servlets/GetEmployeeData");
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setDoOutput(true); // to be able to write.
            urlCon.setDoInput(true); // to be able to read.
            urlCon.setRequestProperty("Content-Type", "application/x-java-serialized-object");
            urlCon.setRequestMethod("POST");

            ObjectOutputStream out = new ObjectOutputStream(urlCon.getOutputStream());
            out.writeObject(empList);
            out.flush();
            out.close();

            /* Read Object */
            ObjectInputStream ois = new ObjectInputStream(urlCon.getInputStream());
            List<Employee> empDetails = (List<Employee>)ois.readObject();
            ois.close();

            /* print employees */
            Iterator<Employee> iter = empDetails.iterator();
            while(iter.hasNext()){
                Employee emp = iter.next();
                System.out.println(emp.getId() +" " + emp.getFirstName() +" " + emp.getLastName());
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}


Output
E512345 Hari Krishna
E512350 Rama Krishna
E512352 Anand Bandaru
E512354 Murugesh Chinnam
E512345 Hari Krishna


Let’s say Servlet Application on step2 listens on below URL.

HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
Returns a URLConnection object that represents a connection to the remote object referred to by the URL.

urlCon.setDoOutput(true); // to be able to write.
urlCon.setDoInput(true); // to be able to read.
A URL connection can be used for input and/or output. Above statements are used to set the values of doOutput and doInput fields to true.

urlCon.setRequestMethod("POST");
Set the method for the URL request to POST.

ObjectOutputStream out = new ObjectOutputStream(urlCon.getOutputStream());
out.writeObject(empList);
Above statements are used to create output stream for this url and send empList object to the URL.

ObjectInputStream ois = new ObjectInputStream(urlCon.getInputStream());
List<Employee> empDetails = (List<Employee>)ois.readObject();
Above statements are used to get the response object from the URL.




No comments:

Post a Comment