Java – How to get Object from HttpResponse


I'm trying to send an object from server to client.

client side:

HttpResponse response = client.execute(request);

server side:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws  IOException 
    PrintWriter out = response.getWriter();
    out.print(new Object());

How do I get the object from the response?
Do i need to use instead:

OutputStream out = response.getOutputStream();

if so which way is more efficient?
example code please 🙂

Best Solution

You cant just send Object.toString() because it does not contain all information about the object. Serialisation is probably what you need. Take a look at that:
The Object you want to send has to implement Serializable. On your server you can then use something like this:

OutputStream out = response.getOutputStream();
oos = new ObjectOutputStream(out);

On the client side you do:

in = new ObjectInputStream(response.getEntity().getContent()); //Android
in = new ObjectInputStream(response.getInputStream()); //Java
ObjcetClass obj = (ObjectClass)in.readObject();