我正在尝试在java中编写一个可以处理&的简单HTTP服务器。读取来自html表单的POST请求
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null);
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange he) throws IOException {
system.out.println("Serving the request");
if (he.getRequestMethod().equalsIgnoreCase("POST")) {
try {
Headers requestHeaders = he.getRequestHeaders();
Set<Map.Entry<String, List<String>>> entries = requestHeaders.entrySet();
int contentLength = Integer.parseInt(requestHeaders.getFirst("Content-length"));
System.out.println(""+requestHeaders.getFirst("Content-length"));
InputStream is = he.getRequestBody();
byte[] data = new byte[contentLength];
int length = is.read(data);
Headers responseHeaders = he.getResponseHeaders();
he.sendResponseHeaders(HttpURLConnection.HTTP_OK, contentLength);
OutputStream os = he.getResponseBody();
os.write(data);
he.close();
} catch (NumberFormatException | IOException e) {
}
}
}
}
}
上面的代码从html表单中读取发布数据,并在浏览器窗口中输出 但我想在java控制台中显示表单信息,那我该怎么做呢?所以请帮助我。