我尝试使用Apache HttpClient(流畅的API)将数据发布到netty服务器。
我尝试了一些变化,我会在这里放两个:
客户端:
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
客户端:
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。
答案 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());
}
}
这是聚合内容的最大长度。你可以自由传递另一个值。