【问题标题】:How to write a Serializable as the body of an http post request?如何将 Serializable 编写为 http post 请求的主体?
【发布时间】:2015-05-04 13:08:22
【问题描述】:

我有一个客户端-服务器应用程序,其中两边都有一个 Serializable 类。我必须使用client 中的ObjectOutputStream 编写该类的对象,并在服务器上使用ObjectInputStream 读取它。

在客户端,我使用的是 Apache HttpClient(4.2 版)。我必须在HttpPost 请求中发送可序列化对象。如何将对象写入HttpPost 请求,以便我可以在服务器上使用ObjectInputStream 读取它?

我正在发送这样的请求:

httpClient.execute(host,postRequest);

【问题讨论】:

    标签: java http-post apache-httpclient-4.x


    【解决方案1】:

    您需要使用包含SerializableEntityBasicHttpEntityEnclosingRequest

    基本上,它看起来像这样:

    BasicHttpEntityEnclosingRequest postRequest = new BasicHttpEntityEnclosingRequest("POST", "uri");
    postRequest.setEntity(new SerializableEntity(yourObject, false));
    

    【讨论】:

    • 我必须在服务器端使用ObjectInputStream.readObject()读取这个可序列化的实体我读到只有使用writeObject(object)写入对象才能成功调用readObject()
    • 这就是SerializableEntity 在幕后所做的事情。
    • @Didier L:非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2021-01-25
    相关资源
    最近更新 更多