Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly read POST request body in a Handler?

Tags:

java

undertow

The code I'm using now:

    Pooled<ByteBuffer> pooledByteBuffer = exchange.getConnection().getBufferPool().allocate();
    ByteBuffer byteBuffer = pooledByteBuffer.getResource();

    int limit = byteBuffer.limit();

    byteBuffer.clear();

    exchange.getRequestChannel().read(byteBuffer);
    int pos = byteBuffer.position();
    byteBuffer.rewind();
    byte[] bytes = new byte[pos];
    byteBuffer.get(bytes);

    String requestBody = new String(bytes, Charset.forName("UTF-8") );

    byteBuffer.clear();
    pooledByteBuffer.free();

It seems to work OK but I'm not sure about the need to clear() ByteBuffer before returning it to the pool. I'm not even sure about using exchange.getConnection().getBufferPool().allocate();. There is not much about it in the documentation.

like image 781
atok Avatar asked Oct 05 '14 14:10

atok


People also ask

How to get request body from post request?

To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String. This takes the body of the request and neatly packs it into our fullName String. We've then returned this name back, with a greeting message.


1 Answers

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.

like image 196
Mwanji Ezana Avatar answered Sep 22 '22 06:09

Mwanji Ezana