I have to serialize an object and send it from a httpserver
i already know how to send a string from the server to the client,but i don’t know how to send a object
So i have this code :
public class Test {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
//this part here shows how to send a string
//but i need to send an object here
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
so i tried to search google but no results,and i tried to change the code (mechanically without knowing well what im doing as im not used to HttpServer’s in java)
this way :
SendResponse obj = new SendResponse();
ObjectOutputStream objOut = new ObjectOutputStream();
t.sendResponseHeaders(200, objOut);
objOut.writeObject(obj);
objOut.close();
but eclipse shows me an error which tells me that the ObjectOutputStream() constructor is not visible and that httpExchange is not applicable for the arguments (int,ObjectInputStream)
Do you have any idea how i can fix this ?
Thank you in advance for your help !
After some hours of trying different things
you have just to replace the
t.sendResponseHeaders(200, objOut);with
t.sendResponseHeaders(200,0);as mentioned by user cyon on this question