4

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 :)
thanks.

Rami
  • 2,098
  • 5
  • 25
  • 37

1 Answers1

4

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: http://java.sun.com/developer/technicalArticles/Programming/serialization/
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);
oos.writeObject(yourSerializableObject);

On the client side you do:

in = new ObjectInputStream(response.getEntity().getContent()); //Android
in = new ObjectInputStream(response.getInputStream()); //Java
ObjcetClass obj = (ObjectClass)in.readObject();
AntonS
  • 700
  • 1
  • 6
  • 23
  • 1
    Alternatively, you can serialize using JSON, there are several projects like jackson http://jackson.codehaus.org/, Gson that can serialize objects quite easily. Cross-platform and easy to debug. – j13r Apr 14 '12 at 15:07
  • I thought that becuase out.print() get object it really sends one, but now i know better, Thanks. about the code above i guess you meant: OutputStream out = response.getOutputStream(); instead of: PrintWriter out = response.getWriter(); and HttpResponse don't have getOutputStream() so my problem remains – Rami Apr 14 '12 at 15:25
  • Oh, yes i meant that. For the response i think you have to use `response.getInputStream()` – AntonS Apr 14 '12 at 15:32
  • response.getEntity().getContent() is the only way to get InputStream. is it good? – Rami Apr 14 '12 at 15:38
  • You are programming for Android, right? Yes, I guess this is fine. – AntonS Apr 14 '12 at 15:46