How to properly read POST request body in a Handler?

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.


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( );
链接地址: http://www.djcxy.com/p/23074.html

上一篇: 弹簧启动远程shell自定义命令

下一篇: 如何在Handler中正确读取POST请求体?