本文介绍了无法使用Netty将JSON发布到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个非常非常基本的问题:使用Netty将HttpRequest转换为POST少量的JSON到服务器.

I'm stuck on a really, really basic problem: Using HttpRequest to POST a wee bit of JSON to a server using Netty.

一旦连接了频道,我就准备如下请求:

Once the channel is connected, I prepare the request like this:

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);

最后一行打印出{"foo":"bar"},它是格式正确的JSON.

The last line prints out {"foo":"bar"}, which is well-formed JSON.

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

However, a really simple echo server I wrote in Python using Flask shows the request, but it has no body or json field, like the body couldn't be parsed into JSON correctly.

当我仅使用curl发送相同的数据时,回显服务器便会正确找到并解析JSON:

When I simply use curl to send the same data, then the echo server does find and parse the JSON correctly:

curl --header "Content-Type: application/json" -d '{"foo":"bar"}' -X POST http://localhost:5000/post_path

我在Netty中的管道由以下部分组成:

My pipeline in Netty is formed with:

return Channels.pipeline(
    new HttpClientCodec(),
    new MyUpstreamHandler(...));

MyUpstreamHandler扩展SimpleChannelUpstreamHandler的位置,是在通道连接后尝试发送HttpRequest的原因.

Where MyUpstreamHandler extends SimpleChannelUpstreamHandler and is what attempts to send the HttpRequest after the channel connects.

再次,我全神贯注.任何帮助将不胜感激.

Again, I'm at a total loss. Any help would be greatly appreciated.

推荐答案

不确定http是否保持活动状态,但是如果这样做,则可能必须在标头中发送内容长度.

Not sure if you have http keep alive on or not, but if you do, you may have to send the content length in the header.

这篇关于无法使用Netty将JSON发布到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 05:49