无法使用Netty将JSON POST到服务器

sha*_*ter 4 post json channel netty

我陷入了一个非常非常基本的问题:使用Netty HttpRequestPOST一小部分JSON用于服务器.

一旦频道连接,我就像这样准备请求:

HttpRequest request = new DefaultHttpRequest(
    HttpVersion.HTTP_1_1, HttpMethod.POST, postPath);
request.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json");
String json = "{\"foo\":\"bar\"}";
ChannelBuffer buffer = ChannelBuffers.copiedBuffer(json, CharsetUtil.UTF_8);
request.setContent(buffer);

channel.write(request);
System.out.println("sending on channel: " + json);
Run Code Online (Sandbox Code Playgroud)

打印出最后一行{"foo":"bar"},这是格式良好的JSON.

但是,我使用Flask在Python中编写的一个非常简单的echo服务器显示了请求,但它没有body或者json字段,就像正文无法正确解析为JSON一样.

当我只是curl用来发送相同的数据时,echo服务器确实正确地找到并解析JSON:

curl --header "Content-Type: application/json" -d '{"foo":"bar"}' -X POST http://localhost:5000/post_path
Run Code Online (Sandbox Code Playgroud)

我在Netty的管道形成了:

return Channels.pipeline(
    new HttpClientCodec(),
    new MyUpstreamHandler(...));
Run Code Online (Sandbox Code Playgroud)

其中MyUpstreamHandler延长SimpleChannelUpstreamHandler而这也正是试图发送HttpRequest通道连接后.

再一次,我完全失去了.任何帮助将不胜感激.

Jes*_*jan 7

正如Veebs所说,你必须设置一些http标头,我也有同样的问题并且丢失了几个小时,我得到了以下代码:).

    import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*;

    ......  

    HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post_path");

    final ChannelBuffer content = ChannelBuffers.copiedBuffer(jsonMessage, CharsetUtil.UTF_8);

    httpRequest.setHeader(CONTENT_TYPE, "application/json");
    httpRequest.setHeader(ACCEPT, "application/json");

    httpRequest.setHeader(USER_AGENT, "Netty 3.2.3.Final");
    httpRequest.setHeader(HOST, "localhost:5000");

    httpRequest.setHeader(CONNECTION, "keep-alive");
    httpRequest.setHeader(CONTENT_LENGTH, String.valueOf(content.readableBytes()));

    httpRequest.setContent(content);

    channel.write(httpRequest);
Run Code Online (Sandbox Code Playgroud)