发送和接收JSON

时间:2013-10-07 11:46:39

标签: netty

我正在使用Apache HttpComponets将这样的数据发布到Netty。我使用Gson来工作JSON。

Request.Post("http://localhost:9090/print").bodyString(getJSon(), ContentType.APPLICATION_JSON),

此netty代码似乎没有收到JSON响应。我确信我的代码是错误的。这可能是什么错误?

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
                                                    throws Exception {
    logger.info( "channelRead" + msg );
    if( msg instanceof HttpRequest ){
        this.request = ( HttpRequest ) msg;
        logger.info( "[" + request.getUri()  + "]");
    }
    if( msg instanceof HttpContent ){
        HttpContent content = (HttpContent)msg;
        ByteBuf buf = content.content();
        logger.info( "[" + buf.toString(CharsetUtil.UTF_8)   + "]");
           if (msg instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) msg;
                writeResponse( trailer, ctx);
           }
    }
}



private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    logger.info( getJSon() );
    ByteBuf response = Unpooled.copiedBuffer( getJSon(),
                                              CharsetUtil.UTF_8);

    ctx.write( response );
    /* Where is 'isKeepAlive' method in the API ? */
    //boolean keepAlive = isKeepAlive(request);
    //keepAlive;
    return false;  
}

1 个答案:

答案 0 :(得分:0)

你需要调用ctx.writeAndFlush(...)来实际将它刷新到套接字。