如何使用Netty 4.0.17向JSON主体发送POST请求

lan*_*ter 5 post json netty

如何使用Netty 4.0.17向JSON主体发送POST请求?我找到了那个方法: HttpPostRequestEncoder.addBodyHttpData()但是不能用它.我不知道它是怎么回事,也不确定那个方法是我需要的.请帮助别人!

小智 9

以下代码片段为Netty 4.0.20 Final工作.它基于HttpSnoopClient示例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);
Run Code Online (Sandbox Code Playgroud)