我必须序列化对象并从httpserver发送它
我已经知道如何将字符串从服务器发送到客户端,但是我不知道如何发送对象
所以我有这个代码:
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();
}
}
}
所以我试图搜索谷歌,但没有结果,并且我试图更改代码(机械地不知道即时通讯在做什么,因为即时通讯不习惯于Java中的HttpServer)
这条路 :
SendResponse obj = new SendResponse();
ObjectOutputStream objOut = new ObjectOutputStream();
t.sendResponseHeaders(200, objOut);
objOut.writeObject(obj);
objOut.close();
但是日食显示了一个错误,告诉我ObjectOutputStream()构造函数不可见,并且httpExchange不适用于参数(int,ObjectInputStream)
你有什么主意我可以解决这个问题吗?
预先感谢您的帮助 !
最佳答案
您可以使用一个OutputStream作为参数来访问构造函数
ObjectOutputStream objOut = new ObjectOutputStream( the http or any other output stream here );
ObjectOutputStream的构造函数发送一些头字节,而ObjectInputStream的构造函数期望这些头字节。您应该为每个对象创建一个新的ObjectOutputStream和一个新的ObjectInputStream,或者为所有对象仅创建一个ObjectOutputStream和ObjectInputStream。
一个更简单的替代方法可能是google gson,它易于使用,并且可以将java类转换为json字符串,也可以采用相反的方式。