如何在Handler中正确读取POST请求正文? [英] How to properly read POST request body in a Handler?

查看:61
本文介绍了如何在Handler中正确读取POST请求正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在使用的代码:

  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

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请求正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆