HTTP request using Netty

I just started netty and I am really disappointed with the documentation provided on their website.

I am trying to connect to a URL using Netty .. I took a sample client from your site and changed it to suit my requirement.

The code:

public class NettyClient { public static void main(String[] args) throws Exception { String host = "myUrl.com/v1/parma?param1=value"; int port = 443; EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ClientHandler()); ch.pipeline().addLast("encoder", new HttpRequestEncoder()); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); } } } 

But the problem is that it only expects a URL without request parameters. How to pass request parameters using url? and please provide me with a link to some good documentation for Netty 4 ..

EDIT

Client code after linking to the example mentioned in the answer:

 URI uri = new URI("myUrl.com/v1/parma?param1=value"); String scheme = uri.getScheme() == null? "http" : uri.getScheme(); String host = "myUrl.com"; int port = 443; boolean ssl = "https".equalsIgnoreCase(scheme); // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new NettyClientInitializer(ssl)); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); //request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); /*// Set some example cookies. request.headers().set( HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode( new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); */ // Send the HTTP request. ch.writeAndFlush(request); // Wait for the server to close the connection. ch.closeFuture().sync(); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); } 

handler code:

 public class ClientHandler extends SimpleChannelInboundHandler<HttpObject> { @Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; System.out.println("STATUS: " + response.getStatus()); System.out.println("VERSION: " + response.getProtocolVersion()); System.out.println(); if (!response.headers().isEmpty()) { for (String name: response.headers().names()) { for (String value: response.headers().getAll(name)) { System.out.println("HEADER: " + name + " = " + value); } } System.out.println(); } if (HttpHeaders.isTransferEncodingChunked(response)) { System.out.println("CHUNKED CONTENT {"); } else { System.out.println("CONTENT {"); } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; System.out.print(content.content().toString(CharsetUtil.UTF_8)); System.out.flush(); if (content instanceof LastHttpContent) { System.out.println("} END OF CONTENT"); } } } @Override public void exceptionCaught( ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } 

initialization code:

 public class NettyClientInitializer extends ChannelInitializer<SocketChannel> { private final boolean ssl; public NettyClientInitializer(boolean ssl) { this.ssl = ssl; } @Override public void initChannel(SocketChannel ch) throws Exception { // Create a default pipeline implementation. ChannelPipeline p = ch.pipeline(); p.addLast("log", new LoggingHandler(LogLevel.INFO)); // Enable HTTPS if necessary. /* if (ssl) { SSLEngine engine = SecureChatSslContextFactory.getClientContext().createSSLEngine(); engine.setUseClientMode(true); p.addLast("ssl", new SslHandler(engine)); } */ p.addLast("codec", new HttpClientCodec()); // Remove the following line if you don't want automatic content decompression. // p.addLast("inflater", new HttpContentDecompressor()); // Uncomment the following line if you don't want to handle HttpChunks. p.addLast("aggregator", new HttpObjectAggregator(1048576)); p.addLast("handler", new ClientHandler()); } } 
+7
java netty
source share
2 answers

Currently, your code only handles a low-level connection. Indeed, at this level, only the host name and port can be used.

For an HTTP request, you must build an HttpRequest object and send it over the pipe. In this request object, you define the request parameters and all such things.

The Netty website has tons of sample code about the features of the HTTP client - look like this !

+3
source

In this example, the problem is the constructor for the DefaultHttpRequest uri.getRawPath () parameter. Calling this method does NOT return query parameters. It works in this case, because the Snoop example did not have query parameters. Substituting uri.toASCIIString (), returns an encoded uri with request parameters. To prove this to yourself, instead of having a method call in a method call (a bad idea for this reason, add an operator

 String url = uri.getRawPath(); 

and look at the string url.

I had the same problem. I did this initially in servlets for many years, but now I tried to do it in a Netty application.

Therefore, the new code will be:

 String path = uri.toASCIIString(); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, path); 
+1
source

All Articles