我陷入了一个非常非常基本的问题:使用 HttpRequest
将一小段 JSON 内容POST
到使用 Netty 的服务器。
连接 channel 后,我将像这样准备请求:
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。
但是,我使用 Flask 用 Python 编写的一个非常简单的回显服务器显示了请求,但它没有 body
或 json
字段,就像主体不能正确解析为 JSON。
当我简单地使用 curl
发送相同的数据时,echo 服务器确实会正确找到并解析 JSON:
curl --header "Content-Type: application/json" -d '{"foo":"bar"}' -X POST http://localhost:5000/post_path
我在 Netty 中的管道是由以下内容组成的:
return Channels.pipeline(
new HttpClientCodec(),
new MyUpstreamHandler(...));
其中 MyUpstreamHandler
扩展了 SimpleChannelUpstreamHandler
,并在 channel 连接后尝试发送 HttpRequest
。
我再一次完全迷失了。任何帮助将不胜感激。
最佳答案
正如 Veebs 所说,你必须设置一些 http header ,我也遇到了同样的问题并丢失了几个小时,我使用以下代码让它工作:)。
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);
关于json - 无法使用 Netty 将 JSON 发布到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9898279/