java - 使用 Apache HttpClient 将数据发布到 netty

标签 java http netty

我正在尝试使用 Apache HttpClient(Fluent API)将数据 POST 到 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();
        }
    }
}

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

最佳答案

要解决该问题,您需要 offer()发送至 HttpContent 的消息的所有 block ( HttpPostRequestDecoder )在调用getBodyHttpDatas()之前,或者您也可以只添加 HttpObjectAggregator处理程序就在 channel 管道的处理程序之前。如果您这样做,HttpObjectAggregator将为您收集所有 block 并生成一个 FullHttpRequest代替多个 block 。路过FullHttpRequest而不是普通的HttpRequestHttpPostRequestDecoder的构造函数消除了 offer() 的需要 block 。

所以你只需要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());
    }
}

1048576这是聚合内容的最大长度。您可以随意传递另一个值。

关于java - 使用 Apache HttpClient 将数据发布到 netty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23989217/

相关文章:

java - String replace() 和 replaceAll() 的区别

java - 当 XSD 元素没有定义类型(类型 ur-type)但 SOAP 响应中返回子类型时,Axis2 会失败?

java - JDBC中如何获取插入ID?

c# - 在 HttpWebRequest 中关闭自动重定向

java - 每个 netty worker 每秒唤醒 2 次。为什么?

Linux - 关闭的连接太多

java - 在 Selenium 中使用带有水平滚动条的 WebTables

c++ - 如何使用 Android ndk 进行 HTTP 请求

http - RESTful 服务应如何公开可变资源的只读属性?

java - Redisson 不关闭使 Java VM 保持打开状态