Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send POST request with JSON body using Netty 4.0.17

Tags:

json

post

netty

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!

like image 268
lanmaster Avatar asked Mar 13 '14 06:03

lanmaster


2 Answers

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);
like image 56
Dmitri Rubinstein Avatar answered Sep 17 '22 22:09

Dmitri Rubinstein


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;
    }
like image 40
Yuriy Vinogradov Avatar answered Sep 17 '22 22:09

Yuriy Vinogradov