Pass complex object into RESTful service


Suppose, I have Employee.java class.
public class Employee {
     private String firstName;
     private String lastName;
     private String city;
    // getter
    // setter
    // override toString() to print the variables

}

I want to set values to Employee class through REST service:

@POST
@Path("/saveemployee")
@Consumes(MediaType.APPLICATION_JSON)
public Response saveEmployee(Employee employee){
    Response response  = null;
    System.out.println(employee.toString());
    // further procees to store into db
    return response;
}



Now, I want to call this rest service inside my java class:



import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import com.ibm.json.java.JSONObject; // Any JSON

....................
....................

try {

    JSONObject employeeJson = new JSONObject();
    employeeJson.put("firstName", "Pankaj");
    employeeJson.put("lastName", "Lilhare");
    employeeJson.put("city", "Pune");
       
    // {"firstName":"Pankaj","lastName":"Lilhare","city":"Pune"}


    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod("http://pankaj-lilhare.blogspot.in/employee/saveemployee");
    RequestEntity re = new StringRequestEntity(employeeJson.toString(), "application/json", "UTF-8");
    postMethod.setRequestEntity(re);
    int returnCode = client.executeMethod(postMethod);
    if (returnCode >= 200 && returnCode < 300) {
      String res = postMethod.getResponseBodyAsString();
       // REPONSE
    }
    } catch (Exception e) {
        e.printStackTrace();
    }


Comments

Popular posts from this blog

XML Parsing in IBM BPM

Type conversion in IBM BPM

Parse the JSON in IBM BPM