how to send an object with URLConnection?

httpurlconnection, java, urlconnection

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.

Problem

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.

Original source

Related problems