问题描述
我正在尝试使用Apache HttpClient(流畅的API)将数据发布到netty服务器。
I'm trying to use Apache HttpClient (the fluent API) to POST data to a netty server.
我尝试了一些变化,我会把两个放在这里:
I've tried a few variations, I'll put two here:
客户:
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()会抛出:
Calling getBodyHttpDatas() throws a:
io.netty.handler.codec.http.multipart.HttpPostRequestDecoder$NotEnoughDataDecoderException
2.
客户:
2.
Client:
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。
This doesn't print any output - decoder.hasNext() is false.
推荐答案
要解决此问题,您需要 offer ()
在调用<$ c之前,消息到 HttpPostRequestDecoder
的所有块( HttpContent
) $ c> getBodyHttpDatas(),或者您可以在处理程序之前将 HttpObjectAggregator
处理程序添加到通道的管道中。如果你这样做, HttpObjectAggregator
将为你收集所有块并产生一个 FullHttpRequest
来代替多个块。将 FullHttpRequest
而不是普通的 HttpRequest
传递给 HttpPostRequestDecoder
's构造函数消除了 offer()
块的需要。
To solve the problem you either need to offer()
all chunks (HttpContent
) of a message to HttpPostRequestDecoder
before calling getBodyHttpDatas()
, or alternatively you can just add the HttpObjectAggregator
handler right before your handler to the channel's pipeline. If you do so, HttpObjectAggregator
will collect all chunks for you and produce a single FullHttpRequest
in place of multiple chunks. Passing FullHttpRequest
instead of an ordinary HttpRequest
to HttpPostRequestDecoder
's constructor eliminates need to offer()
chunks.
所以你只需要管道。添加处理程序之前添加(新的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
这是聚合内容的最大长度。您可以自由传递另一个值。
1048576
here is the maximum length of the aggregated content. You are free to pass another value.
这篇关于使用Apache HttpClient将数据发布到netty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!