How to send POST request with JSON body using Netty 4.0.17?
I was find that method:
HttpPostRequestEncoder.addBodyHttpData()
but cannot use it.
I don't know how it is and not sure that method is that i need.
Please help someone!
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);
Here is working example:
private DefaultFullHttpRequest createReq(final URI uri, final CharSequence body) throws Exception {
DefaultFullHttpRequest request;
if (body == null) {
request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
} else {
request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath());
request.headers().set(HttpHeaders.Names.CONTENT_TYPE,"application/json");
request.content().writeBytes(body.toString().getBytes(CharsetUtil.UTF_8.name()));
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH,request.content().readableBytes());
}
request.setUri(uri.toString());
request.headers().set(HttpHeaderNames.HOST, uri.getHost());
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
return request;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With