Saturday, December 20, 2008

Send an Object using HttpClient

I was looking for a way to send an Object (in my case, a Class) using HttpClient.
This is how I did it:
PostMethod httpMethod =new PostMethod(servletName);
HttpMethodParams httpMethodParams = new HttpMethodParams();
httpMethodParams.setParameter("Object Name", Object);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(tableDataTO);
ByteArrayRequestEntity byteArrayRequestEntity = new ByteArrayRequestEntity(bos.toByteArray());
httpMethod.setRequestEntity(byteArrayRequestEntity);
HttpClientManager.getInstance().executeRequest(httpMethod);


and in the other side, the Servlet side:

InputStream inputStream = request.getInputStream();
ObjectInputStream oos = new ObjectInputStream(inputStream);
ClassName className = null;
try {
className  = (ClassName ) oos.readObject();
} catch (ClassNotFoundException e) {
log.error("Unable to get ClassName  object from the request", e);
}

No comments: