mercredi 15 avril 2015

How to use HttpEntity and PostForObject in resttemplate

I'm trying to store an employee object into mongodb using the Spring restful webservices and resttemplate's postForObject.


Here I have used HttpEntity and postForObject to post the employee object to restful webservice.


In the restful webservice,I'm trying to retrieve the employee Object fields through @FormParam annotation.


I'm able to insert a record into mongodb but the fields are stored as null like this: { "_id" : ObjectId("552e133ee4b0b6b3d3154262"), "client_ip" : null, "start_time" : null, "end_time" : null }



My client code:
================
RestTemplate restTemplate = new RestTemplate();
Employee emp = new Employee();
emp.setClientIp("188.96.258.136");
emp.setStartTime("1345678786789");
emp.setEndTime("1341859801516");

List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new MappingJackson2HttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Employee> entity = new HttpEntity<Employee>(emp, headers);


Employee result2 = restTemplate.postForObject("http://localhost:8080/restful/insert/post", entity, Employee.class);

My RestfulWebservice code:
===========================

@POST
@Path("/post")
@Produces(MediaType.APPLICATION_JSON)
@Consumes({MediaType.APPLICATION_JSON,MediaType.TEXT_PLAIN})
public Response postData(@FormParam("client_ip") String client_ip,
@FormParam("start_time") String start_time, @FormParam("end_time") String end_time)
throws UnknownHostException, MongoException {
String json = null;
Mongo mongo = new Mongo("192.168.7.102", 27017);
DB db = mongo.getDB("sample");

DBCollection col = db.getCollection("data");
DBObject dbo = new BasicDBObject();
dbo.put("client_ip",client_ip );
dbo.put("start_time",start_time );
dbo.put("end_time",end_time );
col.insert(dbo);

json = JSON.serialize(dbo);


return Response.status(200).entity(json).build();
}


Can anyone suggest me how to post an employee object into mongodb using the resttemplate and how to retrieve the fields at the restful webservice end.


Thank in advance


Aucun commentaire:

Enregistrer un commentaire