Question

I am using Apache's HttpClient to call a servlet from a Java class. I want to send an object to the servlet which should save the object using Serialization. How to send the object to the servlet?

public static void main(String[] args) {

        Names names = new Names();
        names.setName("ABC");
        names.setPlace("Bangalore");
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://localhost:9080/HttpClientPractice/FirstServlet");
//Rest of the code

In the above code snippet, I have another class Names and I want to send an object of Names to the servlet. Right now I am only calling the servlet with the URI, but I want to pass the object.

Thanks!

Was it helpful?

Solution

Convert the object to a Json String using a Library like Gson in the class you have shown and add this string as a query parameter - showing you how to do it with Gson.

Gson gson = new Gson();
String json = gson.toJson(names);
HttpGet httpget = new HttpGet("http://localhost:9080/HttpClientPractice/FirstServlet?obj="+json);

In the class you are going to store this object, do a fromJson (method in the Gson library)

Gson gson = new Gson();
Names names = fromJson(json, Names.class);

OTHER TIPS

The best way to send the object to a URL is send it either as XML or JSON instead of serializing object and sending it.

One way to send the object if your method remains the same is to attach the object values in url as query string e.g:
http://localhost:9080/HttpClientPractice/FirstServlet?name=ABC&place=Banglore
The other way would be to change the request method to POST and send object as XML or JSON content.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top