如何从POST获取内容?

时间:2014-09-14 10:31:14

标签: java post netty

我开始学习Netty 4 Http Server,但我已经遇到了问题。我们怎样才能以最简单的方式从POST请求中获取内容?

我浏览Netty的文档,但它很复杂。

提前致谢!


编辑: 我使用此代码接收数据。

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;

import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpRequest;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import java.io.IOException;
import java.util.List;

public class HttpServerHandler extends ChannelInboundHandlerAdapter
{

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx)
    {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException
    {
        if (msg instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) msg;

            if (HttpHeaders.is100ContinueExpected(req)) {
                ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
            }
            boolean keepAlive = HttpHeaders.isKeepAlive(req);

            /*
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req);
            List<InterfaceHttpData> list = decoder.getBodyHttpDatas();
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
            }
            */

            String message = "Lorem ipsum dolorem";
            byte[] byty = message.getBytes();

            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(byty));
            response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            response.headers().set(CONTENT_TYPE, "text/plain; charset=utf-8");
            response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

            if (!keepAlive) {
                ctx.write(response).addListener(ChannelFutureListener.CLOSE);
            } else {
                response.headers().set(CONNECTION, Values.KEEP_ALIVE);
                ctx.write(response);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
    {
        cause.printStackTrace();
        ctx.close();
    }
}

正如您所看到的,有三条注释行返回异常:

  

io.netty.handler.codec.http.multipart.HttpPostRequestDecoder $ NotEnoughDataDecoderException     在   io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.getBodyHttpDatas(HttpPostRequestDecoder.java:339)     在   httpServer.HttpServerHandler.channelRead(HttpServerHandler.java:64)     在   io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)     在   io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)     在   io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:163)     在   io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:147)     在   io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)     在   io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)     在   io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:787)     在   io.netty.channel.nio.AbstractNioByteChannel $ NioByteUnsafe.read(AbstractNioByteChannel.java:130)     在   io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)     在   io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)     在   io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)     在io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)at   io.netty.util.concurrent.SingleThreadEventExecutor $ 2.run(SingleThreadEventExecutor.java:116)     在   io.netty.util.concurrent.DefaultThreadFactory $ DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)     在java.lang.Thread.run(Thread.java:745)

发送代码如下所示:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://127.0.0.1:8030", true);
xmlhttp.send("json=value");

1 个答案:

答案 0 :(得分:0)

看起来你在这里混合了一些东西。解码器可能更适合从ServerBootstrap调用的管道初始化器。

以下示例摘自曼宁出版社的书籍Netty in Action

    public class HttpDecoderEncoderInitializer
        extends ChannelInitializer<Channel> {
        private final boolean client;
        public HttpDecoderEncoderInitializer(boolean client) {
            this.client = client;
        }
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (client) {
                pipeline.addLast("decoder", new HttpResponseDecoder());
                pipeline.addLast("encoder", new HttpRequestEncoder());
            } else {
                pipeline.addLast("decoder", new HttpRequestDecoder());
                pipeline.addLast("encoder", new HttpResponseEncoder());
            }
        }
    }

API文档/源代码也有一些易于遵循的HTTP示例(在示例文件夹中)。

您将解码器放入管道中,您可以直接在处理程序中的req对象上操作,因为它将被解码并且#34;从字节到HttpMessage对象。