How to properly read POST request body in a Handler?

試著忘記壹切 提交于 2019-12-01 16:13:19
Mwanji Ezana

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.

@atok, I use your method for a while, but sometimes I get an empty body when the stream is closed before the read call. This works like charm:

BufferedReader reader = null;
StringBuilder builder = new StringBuilder( );

try {
    exchange.startBlocking( );
    reader = new BufferedReader( new InputStreamReader( exchange.getInputStream( ) ) );

    String line;
    while( ( line = reader.readLine( ) ) != null ) {
        builder.append( line );
    }
} catch( IOException e ) {
    e.printStackTrace( );
} finally {
    if( reader != null ) {
        try {
            reader.close( );
        } catch( IOException e ) {
            e.printStackTrace( );
        }
    }
}

String body = builder.toString( );
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.BlockingHandler;


public static void main(String[] args) {

    Undertow server = Undertow.builder()
            .addHttpListener(8087, "xx.xx.xx.xx")
            .setHandler(Handlers.pathTemplate().add("/webhook", new BlockingHandler(new ItemHandler())))
            .build();
    server.start();
}

static class ItemHandler implements HttpHandler {


    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
       exchange.getInputStream());
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!