How to send POST request with JSON body using Netty 4.0.17

Following code snippet worked for me with Netty 4.0.20 Final. It is based on HttpSnoopClient example http://netty.io/4.0/xref/io/netty/example/http/snoop/HttpSnoopClient.html:

// Prepare the HTTP request.
String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
FullHttpRequest request = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath());

request.headers().set(HttpHeaders.Names.HOST, host);
request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); // or HttpHeaders.Values.CLOSE
request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
request.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json");
ByteBuf bbuf = Unpooled.copiedBuffer("{\"jsonrpc\":\"2.0\",\"method\":\"calc.add\",\"params\":[1,2],\"id\":1}", StandardCharsets.UTF_8);
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, bbuf.readableBytes());
request.content().clear().writeBytes(bbuf);

// Send the HTTP request.
channel.writeAndFlush(request);

Tags:

Json

Post

Netty