Reputation: 77
I am trying to write a simple HTTP server in java that can handle & read POST requests which is coming from html form
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) {
}
}
}
}
}
above code read the post data from html form and gives output on browsers window but i want to display the form information in java console so how can i do that? so please help me.
Upvotes: 1
Views: 10457
Reputation: 564
I did not test it because I have no form ready to send a POST message or don't know how I can create a HTTP POST message from scratch.
You can print the data you already read to the console by using the String class:
System.out.print(new String(data));
Upvotes: 2