How to send serialized object to a servlet using Apache HttpClient

天涯浪子 提交于 2019-12-14 02:25:37

问题


I have a Main() class where I serialize an object of a class called Names. I am using Apache HttpClient's HttpPost() to call a servlet.

public static void main(String[] args) {

    Names names = new Names();
    names.setName("ABC");
    names.setPlace("Bangalore");
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Name.txt"));
    out.writeObject(names);
    out.close();

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:6080/HttpClientGson/FirstHttpPostServlet");

Now, how do I send the ObjectOutputStream object? I wrote the following line httppost.setEntity(out)

But setEntity() can only take objects of HttpEntity type. Is there any other method of HttpClient that I can use to send serialized object?


回答1:


You could SerializableEntity class shipped with HttpClient

httpost.setEntity(new SerializableEntity(mySerializableObj, false));

Please note, though, that binary object serialization should be used only when absolutely required. Other serialization formats such as XML or JSON should generally be preferred.




回答2:


You can use XStream to serialize an object to XML/JSON. http://x-stream.github.io/ and then to pass it.



来源:https://stackoverflow.com/questions/12794868/how-to-send-serialized-object-to-a-servlet-using-apache-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!