Rajath
Rajath

Reputation: 2188

How to send serialized object to a servlet using Apache HttpClient

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?

Upvotes: 1

Views: 5255

Answers (2)

Alex
Alex

Reputation: 11579

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

Upvotes: 0

ok2c
ok2c

Reputation: 27593

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.

Upvotes: 2

Related Questions