如何从HttpResponse获取Object? [英] How to get Object from HttpResponse?
问题描述
我正在尝试从服务器向客户端发送对象。
I'm trying to send an object from server to client.
客户端:
HttpResponse response = client.execute(request);
服务器端:
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();
如果这样哪种方式更有效?
示例代码请:)< br>
谢谢。
if so which way is more efficient?
example code please :)
thanks.
推荐答案
您无法发送Object.toString(),因为它不包含有关该对象的所有信息。
序列化可能就是你所需要的。请看一下: http://java.sun.com/developer/technicalArticles/编程/序列化/
您要发送的对象必须实现Serializable。
在您的服务器上,您可以使用以下内容:
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);
在客户端,您可以:
in = new ObjectInputStream(response.getEntity().getContent()); //Android
in = new ObjectInputStream(response.getInputStream()); //Java
ObjcetClass obj = (ObjectClass)in.readObject();
这篇关于如何从HttpResponse获取Object?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!