使用Apache HttpClient将数据发布到netty

时间:2014-06-02 07:22:09

标签: java http netty

我尝试使用Apache HttpClient(流畅的API)将数据发布到netty服务器。

我尝试了一些变化,我会在这里放两个:

1

客户端:

Request.Post(uri).bodyString("content value", ContentType.TEXT_PLAIN).useExpectContinue().execute().returnContent().asString();

服务器:

final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);              
System.out.println(decoder.getBodyHttpDatas().size());

调用getBodyHttpDatas()会抛出:

io.netty.handler.codec.http.multipart.HttpPostRequestDecoder$NotEnoughDataDecoderException

2

客户端:

Request.Post(uri).bodyForm(new BasicNameValuePair("value", "content value")).useExpectContinue().execute().returnContent().asString();

服务器:

final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);
final InterfaceHttpData data1 = decoder.getBodyHttpData("value");

while (decoder.hasNext()) {
    final InterfaceHttpData data = decoder.next();
    if (data != null) {
        try {
            Attribute attribute = (Attribute) data;
            System.out.println(attribute.getValue());
        } finally {
            data.release();
        }
    }
}

这不打印任何输出 - decoder.hasNext()为false。

1 个答案:

答案 0 :(得分:4)

要解决此问题,您需要offer()在致电HttpContent之前向HttpPostRequestDecoder发送消息的所有块(getBodyHttpDatas()),或者您只需添加{处理程序之前的{1}}处理程序到通道的管道。如果您这样做,HttpObjectAggregator将为您收集所有块并生成一个HttpObjectAggregator来代替多个块。将FullHttpRequest而不是普通的FullHttpRequest传递给HttpRequest的构造函数,无需HttpPostRequestDecoder个块。

所以在添加处理程序之前,您只需要offer()。例如:

pipeline.addLast(new HttpObjectAggregator(1048576))

public class YourServerInitializer extends ChannelInitializer<SocketChannel> { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(1048576)); pipeline.addLast(new YourServerHandler()); } } 这是聚合内容的最大长度。你可以自由传递另一个值。