Question

My goal is to send a object from a client application to a server using URLConnection The object User :

 Public class user {
     String nom;
     Integer id ;
     boolean sex;

    }

I don't want to send it field by field but as an object.

Was it helpful?

Solution

You can send the object with an ObjectOutputStream.
A requirement for this would be that you implement the java.io.Serializable interface.

public class User implements Serializable {
    ......
}

Now to send an User-Object:

User usr = new User();    

Url url;
HttpURLConnection conn;
ObjectOutputStream objout;
try {
    url = new Url("http://192.160.1.1");
    conn  = (HttpURLConnection) url.getConnection();

    conn.setDoOutput(true); //this is to enable writing
    conn.setDoInput(true);  //this is to enable reading

    out = new ObjectOutputStream(conn.getOutputStream());
    out.writeObject(usr);
    out.close();
}

Now that object will be sent to the specified url.

OTHER TIPS

You can use json to achieve your requirement.

In addition, followings may help you for learning Json.

http://www.mkyong.com/tutorials/java-json-tutorials/

How do you return a JSON object from a Java Servlet

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