How to send serialized object to a servlet using Apache HttpClient
Question
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?
Solution
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.
OTHER TIPS
You can use XStream to serialize an object to XML/JSON. http://x-stream.github.io/ and then to pass it.