1
votes

my client send http request to a netty http server via post, and the post body is format of json. My question is how to decode post body in netty http server? I have found some code:

HttpPostRequestDecoder decoder = new HttpPostRequestDecoder( new DefaultHttpDataFactory(false), request );
                /*InterfaceHttpData*/String data = decoder.getBodyHttpDatas().toString();

How to extract post body to json since the client send post body as format of json? I am using netty 4

2

2 Answers

1
votes

In your http server you should have handler, that extended from ChannelInboundHandlerAdapter.

And there you overriding method: channelRead, something like this:

public class MyHttpServerHandler extends ChannelInboundHandlerAdapter{
    private static final ObjectMapper JsonMapper = new ObjectMapper();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        if (msg instanceof HttpRequest) {
            LOG.info("I'm HttpRequest");

            FullHttpRequest req = (FullHttpRequest) msg;

            if (HttpHeaders.is100ContinueExpected(req)) {
                ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
            }

            // here your json
            ObjectNode  data = parseData(req);

        }
    }

    private ObjectNode parseData(FullHttpRequest req){
        ObjectNode res;
        try {
            res = JsonMapper.readValue(req.content().toString(CharsetUtil.UTF_8), ObjectNode.class);
            return res;
        }
        catch (IOException e) {

        }
        return null;
    }



    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super. channelUnregistered(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }
}
-1
votes

I wouldn't recommend building an HttpServer using Netty directly. Instead you should https://github.com/RestExpress/RestExpress. RestExpress is basically a wrapper over Netty and it is used to define an API framework backed by a Netty Http Server. So this will easily solve your problem. Parsing an HttpPacket and obtaining the JSON yourself could be a pain. All this is done for you by RestExpress. So do consider using it once.