如何在Handler中正确读取POST请求正文?

编程入门 行业动态 更新时间:2024-10-25 09:27:28
本文介绍了如何在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 或文档.这是使用 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请求正文?

本文发布于:2023-10-09 18:41:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476470.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   如何在   正文   Handler   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!