首页 > 代码库 > netty4 HTTPclient 可添加参数

netty4 HTTPclient 可添加参数

下了netty4的demo,但是发现给例子不能添加参数。所以自己改了一下,用netty实现http协议get请求并追加参数。

HttpSnoopClient.java
 1 import io.netty.bootstrap.Bootstrap; 2 import io.netty.channel.Channel; 3 import io.netty.channel.EventLoopGroup; 4 import io.netty.channel.nio.NioEventLoopGroup; 5 import io.netty.channel.socket.nio.NioSocketChannel; 6 import io.netty.handler.codec.http.ClientCookieEncoder; 7 import io.netty.handler.codec.http.DefaultCookie; 8 import io.netty.handler.codec.http.DefaultFullHttpRequest; 9 import io.netty.handler.codec.http.HttpHeaders;10 import io.netty.handler.codec.http.HttpMethod;11 import io.netty.handler.codec.http.HttpRequest;12 import io.netty.handler.codec.http.HttpVersion;13 import io.netty.handler.ssl.SslContext;14 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;15 import java.net.URI;16 17 /**18  * A simple HTTP client that prints out the content of the HTTP response to19  * {@link System#out} to test {@link HttpSnoopServer}.20  */21 public final class HttpSnoopClient {22 23     static final String URL = System.getProperty("url", "http://www.baidu.com/s");24     static final String PARAM = "?wd=罗龙龙";25 26     public static void main(String[] args) throws Exception {27         URI uri = new URI(URL);28         String scheme = uri.getScheme() == null? "http" : uri.getScheme();29         String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();30         int port = uri.getPort();31         if (port == -1) {32             if ("http".equalsIgnoreCase(scheme)) {33                 port = 80;34             } else if ("https".equalsIgnoreCase(scheme)) {35                 port = 443;36             }37         }38 39         if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {40             System.err.println("Only HTTP(S) is supported.");41             return;42         }43 44         // Configure SSL context if necessary.45         final boolean ssl = "https".equalsIgnoreCase(scheme);46         final SslContext sslCtx;47         if (ssl) {48             sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);49         } else {50             sslCtx = null;51         }52 53         // Configure the client.54         EventLoopGroup group = new NioEventLoopGroup();55         try {56             Bootstrap b = new Bootstrap();57             b.group(group)58              .channel(NioSocketChannel.class)59              .handler(new HttpSnoopClientInitializer(sslCtx));60 61             // Make the connection attempt.62             Channel ch = b.connect(host, port).sync().channel();63             System.out.println("*************"+uri.getRawQuery()+"*************");64             // Prepare the HTTP request.65             HttpRequest request = new DefaultFullHttpRequest(66                     HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()+PARAM);67             request.headers().set(HttpHeaders.Names.HOST, host);68             request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);69             request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);70 71             // Set some example cookies.72             request.headers().set(73                     HttpHeaders.Names.COOKIE,74                     ClientCookieEncoder.encode(75                             new DefaultCookie("my-cookie", "foo"),76                             new DefaultCookie("another-cookie", "bar")));77 78             // Send the HTTP request.79             ch.writeAndFlush(request);80 81             // Wait for the server to close the connection.82             ch.closeFuture().sync();83         } finally {84             // Shut down executor threads to exit.85             group.shutdownGracefully();86         }87     }88 }
HttpSnoopClientHandler.java
import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.handler.codec.http.HttpContent;import io.netty.handler.codec.http.HttpHeaders;import io.netty.handler.codec.http.HttpObject;import io.netty.handler.codec.http.HttpResponse;import io.netty.handler.codec.http.LastHttpContent;import io.netty.util.CharsetUtil;public class HttpSnoopClientHandler extends SimpleChannelInboundHandler<HttpObject> {    @Override    public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {        if (msg instanceof HttpResponse) {            HttpResponse response = (HttpResponse) msg;            System.err.println("STATUS: " + response.getStatus());            System.err.println("VERSION: " + response.getProtocolVersion());            System.err.println();            if (!response.headers().isEmpty()) {                for (String name: response.headers().names()) {                    for (String value: response.headers().getAll(name)) {                        System.err.println("HEADER: " + name + " = " + value);                    }                }                System.err.println();            }            if (HttpHeaders.isTransferEncodingChunked(response)) {                System.err.println("CHUNKED CONTENT {");            } else {                System.err.println("CONTENT {");            }        }        if (msg instanceof HttpContent) {            HttpContent content = (HttpContent) msg;            System.err.print(content.content().toString(CharsetUtil.UTF_8));            System.err.flush();            if (content instanceof LastHttpContent) {                System.err.println("} END OF CONTENT");                ctx.close();            }        }    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {        cause.printStackTrace();        ctx.close();    }}

HttpSnoopClientInitializer.java

 1 import io.netty.channel.ChannelInitializer; 2 import io.netty.channel.ChannelPipeline; 3 import io.netty.channel.socket.SocketChannel; 4 import io.netty.handler.codec.http.HttpClientCodec; 5 import io.netty.handler.codec.http.HttpContentDecompressor; 6 import io.netty.handler.ssl.SslContext; 7  8 public class HttpSnoopClientInitializer extends ChannelInitializer<SocketChannel> { 9 10     private final SslContext sslCtx;11 12     public HttpSnoopClientInitializer(SslContext sslCtx) {13         this.sslCtx = sslCtx;14     }15 16     @Override17     public void initChannel(SocketChannel ch) {18         ChannelPipeline p = ch.pipeline();19 20         // Enable HTTPS if necessary.21         if (sslCtx != null) {22             p.addLast(sslCtx.newHandler(ch.alloc()));23         }24 25         p.addLast(new HttpClientCodec());26 27         // Remove the following line if you don‘t want automatic content decompression.28         p.addLast(new HttpContentDecompressor());29 30         // Uncomment the following line if you don‘t want to handle HttpContents.31         //p.addLast(new HttpObjectAggregator(1048576));32 33         p.addLast(new HttpSnoopClientHandler());34     }35 }

 

netty4 HTTPclient 可添加参数