Can't POST JSON to server using Netty

天涯浪子 提交于 2019-12-04 09:55:35

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.

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