如何在处理程序中正确读取POST请求正文?

2022-09-04 03:22:09

我现在使用的代码:

    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();

它似乎工作正常,但我不确定在将其返回到池之前是否需要ByteBuffer。我甚至不确定是否使用.文档中没有太多关于它的内容。clear()exchange.getConnection().getBufferPool().allocate();


答案 1

读取请求正文的一种更简单方法是调度到工作线程,这样就可以了。HttpExchange#getInputStream()

有两种方法可以执行此操作:使用文档中显示的 调度模式 或 调度模式。下面是使用 :BlockingHandlerBlockingHandler

new BlockingHandler(myHandler)

基本上为您执行调度。BlockingHandler


答案 2

要以非阻塞方式执行此操作,请参阅界面。处理程序的示例可以是:io.undertow.io.Receiver

pathHandler.put("/test", new HttpHandler() {
    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        exchange.getRequestReceiver().receiveFullBytes(new FullBytesCallback() {
            @Override
            public void handle(HttpServerExchange exchange, byte[] message) {
                System.out.println(new String(message));
            }                    
        });

        exchange.getResponseSender().send("Hello World");
    }
});

或者对于 Java 8:

pathHandler.put("/test", (ex) -> {
    ex.getRequestReceiver().receiveFullBytes((e, m) -> {
        System.out.println(new String(m));
    });
    ex.getResponseSender().send("Hello World");
});

推荐