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

时间:2014-03-13 06:02:14

标签: json post netty

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

2 个答案:

答案 0 :(得分:6)

以下代码片段为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);

答案 1 :(得分:0)

这是工作示例:

 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;
    }