通过网络传输对象的方式有很多种,例如 RMI,WebServices。最近在基于 HTTP 作 Web 应用程序,客户端使用 Apache Httpclient。如何通过 Http 连接传输对象呢? 可以利用最传统的对象序列化(Serializable)。要传输的对象类需要实现 Serializable 接口。由于 HttpServletResponse 只能发送 byte[],因此我们需要将对象转化成字节数组,然后发送。
Server 端代码如下 :
sendObjectResponse( HttpServletResponse response )
{
response.setContentType("application/octet-stream");
OutputStream out = response.getOutputStream();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bout);
oos.writeObject(responseObject);
oos.flush();
byte[] byteArry = bout.toByteArray();
bout.close();
oos.close();
out.write(byteArry);
out.flush();
}
Client 端代码如下 :
receiveObjectResponse( )
{
HttpClient client = new HttpClient();
String url = "http:localhost:9080/test";
PostMethod postMethod = new PostMethod( url );
client.executeMethod( postMethod );
InputStream bin = postMethod.getResponseBodyAsStream();
ObjectInputStream ois = new ObjectInputStream(bin);
// get the Object
result = ois.readObject();
bin.close();
ois.close();
// close the post connection
postMethod.releaseConnection();
}