如何使用Apache HttpClient将序列化对象发送到servlet [英] How to send serialized object to a servlet using Apache HttpClient
问题描述
我有一个 Main()
类,我在其中序列化一个名为 Names
的类的对象。我使用 Apache HttpClient
的 HttpPost()
来调用 servlet
。
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");
现在,如何发送 ObjectOutputStream
目的?我写了以下行
httppost.setEntity(out)
Now, how do I send the ObjectOutputStream
object? I wrote the following line
httppost.setEntity(out)
但是 setEntity()
只能接受 HttpEntity
类型的对象。我可以用来发送序列化对象的 HttpClient
的其他方法吗?
But setEntity()
can only take objects of HttpEntity
type. Is there any other method of HttpClient
that I can use to send serialized object?
推荐答案
您可以 SerializableEntity
HttpClient附带的类
You could SerializableEntity
class shipped with HttpClient
httpost.setEntity(new SerializableEntity(mySerializableObj, false));
但请注意,只有在绝对需要时才应使用二进制对象序列化。通常应首选其他序列化格式,如XML或JSON。
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.
这篇关于如何使用Apache HttpClient将序列化对象发送到servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!