How to properly read POST request body in a Handler?

A simpler way to read the request body is to dispatch to a worker thread, which makes HttpExchange#getInputStream() available.

There are two ways of doing this: using a BlockingHandler or the dispatch pattern shown in the documentation. Here's an example of using the BlockingHandler:

new BlockingHandler(myHandler)

The BlockingHandler basically does the dispatch for you.


To do it in non-blocking way please see io.undertow.io.Receiver interface. The example of handler could be:

pathHandler.put("/test", new HttpHandler() {
    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        exchange.getRequestReceiver().receiveFullBytes(new FullBytesCallback() {
            @Override
            public void handle(HttpServerExchange exchange, byte[] message) {
                System.out.println(new String(message));
            }                    
        });

        exchange.getResponseSender().send("Hello World");
    }
});

Or for Java 8:

pathHandler.put("/test", (ex) -> {
    ex.getRequestReceiver().receiveFullBytes((e, m) -> {
        System.out.println(new String(m));
    });
    ex.getResponseSender().send("Hello World");
});

Tags:

Java

Undertow