Question

I found a segment of java code that is claimed to return object using ObjectOutputStream

     OutputStream outstr = response.getOutputStream();
     ObjectOutputStream oos = new ObjectOutputStream(outstr);

     oos.writeObject(process);

     oos.flush();
     oos.close();

response is a HttpServletResponse object. I would like to know how this segment of code works, and how to test it?

Was it helpful?

Solution

Below is a simple example that shows how to read a serialized object via HTTP.

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.ObjectInputStream;

/**
 * This is a simple example to read an object. 
 *
 * This is not production ready code ;-)
 */
public class Sample {

    public static void main(final String [] pArgs) throws Exception {

        // Change SERVER:PORT/PATH to match your application.
        final URL url = new URL("http://SERVER:PORT/PATH");
        final HttpURLConnection conn = (HttpURLConnection)url.openConnection();

        conn.setRequestMethod("GET");
        conn.setReadTimeout(10000);
        conn.connect();

        final ObjectInputStream is 
        = new ObjectInputStream(conn.getInputStream());

        final Object obj = is.readObject();

        if (obj instanceof String) System.out.println((String)obj);
        else // Convert to object and do whatever.

        is.close();
        conn.disconnect();
    }
}

OTHER TIPS

It serializes the object to the servlet's output stream (e.g. the data that would be served in the HTTP response) using Java's default binary serialization protocol (which I'm personally somewhat reluctant to use). For details, see the object serialization spec.

As for how to test it - it depends on the level of testing you want to use. You could use a fake HTTP servlet library, get the response and then try to read it again with an ObjectInputStream, or you could run up the actual servlet container, make an HTTP request and then try to deserialize the response.

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