Java netty 获取 POST 请求内容

标签 java netty

我正在使用 Java 中嵌入的 netty 4.1 并尝试从管道中的客户端 POST 请求中检索数据。我尝试了在网上找到的几个选项,但没有任何效果......

也许有人对此有有用的想法。

向所有提供帮助的人致以问候和感谢。

管道:

    p.addLast ("codec", new HttpServerCodec ());
    p.addLast("decoder", new HttpRequestDecoder());
    p.addLast("encoder", new HttpRequestEncoder());
    p.addLast("handler",new InboundHandlerA());

处理程序:

private static class InboundHandlerA extends ChannelInboundHandlerAdapter{
     @Override
     public void channelActive(ChannelHandlerContext ctx) {
         System.out.println("Connected!");
         ctx.fireChannelActive();
     } 

 public void channelRead (ChannelHandlerContext channelHandlerCtxt, Object msg) throws Exception   {

         System.out.println(msg);
     }
    }

最佳答案

使用 netty 接收 HTTP 请求很简单,您可以使用以下管道来完成此操作:

// Provides support for http objects:
p.addLast("codec", new HttpServerCodec());
// Deals with fragmentation in http traffic: 
p.addLast("aggregator", new HttpObjectAggregator(Short.MAX_VALUE));
// Deals with optional compression of responses:
// p.addLast("aggregator", new HttpContentCompressor());
p.addLast("handler",new InboundHandlerA());

这可以与自定义 SimpleChannelInboundHandler<FullHttpRequest> 一起使用:

public class InboundHandlerA extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        super.channelActive(ctx);
        System.out.println("Connected!");
    } 

    // Please keep in mind that this method 
       will be renamed to messageReceived(ChannelHandlerContext, I) in 5.0.
    @Override
    public void channelRead0 (ChannelHandlerContext ctx, 
                              FullHttpRequest msg) throws Exception {
        // Check for invalid http data:
        if(msg.getDecoderResult() != DecoderResult.SUCCESS ) {
            ctx.close();
            return;
        }

        System.out.println("Recieved request!");
        System.out.println("HTTP Method: " + msg.getMethod());
        System.out.println("HTTP Version: " + msg.getProtocolVersion());
        System.out.println("URI: " + msg.getUri());
        System.out.println("Headers: " + msg.headers());
        System.out.println("Trailing headers: " + msg.trailingHeaders());

        ByteBuf data = msg.content();
        System.out.println("POST/PUT length: " + data.readableBytes());
        System.out.println("POST/PUT as string: ");
        System.out.println("-- DATA --");
        System.out.println(data.toString(StandardCharsets.UTF_8));
        System.out.println("-- DATA END --");

        // Send response back so the browser won't timeout
        ByteBuf responseBytes = ctx.alloc().buffer();
        responseBytes.writeBytes("Hello World".getBytes());

        FullHttpResponse response = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.OK, responseBytes);
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, 
                               "text/plain");
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 
                               response.content().readableBytes());

        response.headers().set(HttpHeaders.Names.CONNECTION, 
                               HttpHeaders.Values.KEEP_ALIVE);
        ctx.write(response);
    }
}

上面的代码打印出传入消息的所有详细信息,包括发布数据。如果您只需要发布数据,则可以添加一个简单的 if 语句来过滤 POST 响应类型

关于Java netty 获取 POST 请求内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36474734/

相关文章:

java - 在 Websphere Portal 8 中以编程方式显式注销用户并重定向到默认登录页面

java - javadoc中模块之间的链接

java - Android ImageView 全屏

java - Netty:在随机位置获取当前 'Channel'

java - 如何捕获netty中的所有异常

java - 客户端 ECC SSL 证书包含 "unknown named curve"

scala - Netty SslHandler 头痛

java - 如何构建表单

java - 使用 Java 查询 XML

Java SSL 握手异常 - "unable to find valid certification path"