Tuesday, July 29, 2008

Sending a java object over HTTP protocol

As you may know HTTP communication is based on strings that are sent back and forth, and if you want to send an object across the wire over HTTP just object serialization isn't enough. You will have to convert your object into an XML string, and stream it in a ByteArrayOutputStream.
Here goes a snippet of my client code:

MethodInvokerBean miBean = new MethodInvokerBean(); //Instantiate your java bean

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

XMLEncoder encoder = new XMLEncoder(buffer); //Assign ByteArrayOutputStream object to your XMLEncoder object

encoder.writeObject(miBean); //Write object on XMLEncoder object
encoder.close(); //close stream

String url = "http://192.168.1.25/BeanDecoder"; //Servlet's URL

//The classes and methods used in the block below to establish connection with the servlet and pass my object as a parameter come from the HTTP apache client library called commons-httpclient

PostMethod post = new PostMethod(url);
NameValuePair[] nvp = new NameValuePair[1];
nvp[0] = new NameValuePair("bean",buffer.toString());
post.setRequestBody(nvp);
HttpClient httpClient = new HttpClient();

try
{
int result = httpClient.executeMethod(post);
System.out.println(post.getResponseBodyAsString());
System.out.println("HTTP Status: " + result);
}
...


Let's see the servlet's code now:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String beanXML= req.getParameter("bean");
ByteArrayInputStream bais = new ByteArrayInputStream(beanXML.getBytes());
XMLDecoder decoder = new XMLDecoder(bais);
MethodInvokerBean miBean = null;
miBean = (MethodInvokerBean)decoder.readObject();
}