我现在正在使用的代码:
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 []个字节=新的byte [pos];byteBuffer.get(bytes);字符串requestBody =新的String(bytes,Charset.forName("UTF-8"));byteBuffer.clear();pooledByteBuffer.free();似乎工作正常,但是我不确定在将其返回到池之前是否需要 clear() ByteBuffer.我什至不确定要使用 exchange.getConnection().getBufferPool().allocate(); .在文档中没有太多关于此的内容.
解决方案读取请求正文的一种更简单的方法是分派给工作线程,这使 HttpExchange#getInputStream()可用./p>
有两种方法:使用 BlockingHandler 或文档.这是使用 BlockingHandler 的示例:
新的BlockingHandler(myHandler)
BlockingHandler 基本上为您执行分派.
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.
更多推荐
如何在Handler中正确读取POST请求正文?
发布评论