如何使用 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屋!