Can't POST JSON to server using Netty

只愿长相守 提交于 2019-12-06 06:15:57

问题


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

The last line prints out {"foo":"bar"}, which is well-formed 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.

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

My pipeline in Netty is formed with:

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

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.


回答1:


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.




回答2:


As Veebs said, you have to set some http headers, I too had same the problem and lost for hours, I got it working with following code :).

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


来源:https://stackoverflow.com/questions/9898279/cant-post-json-to-server-using-netty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!