java 如何从 HttpResponse 获取对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10154477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:49:58  来源:igfitidea点击:

How to get Object from HttpResponse?

java

提问by Rami

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.

如果是这样,哪种方式更有效?
示例代码请:)
谢谢。

采纳答案by AntonS

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:

您不能只发送 Object.toString(),因为它不包含有关对象的所有信息。序列化可能是您所需要的。看一看:http: //java.sun.com/developer/technicalArticles/Programming/serialization/
您要发送的对象必须实现可序列化。在您的服务器上,您可以使用以下内容:

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();