博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
netty4 HTTPclient 可添加参数
阅读量:4624 次
发布时间:2019-06-09

本文共 6953 字,大约阅读时间需要 23 分钟。

下了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
{ @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
{ 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 }

 

转载于:https://www.cnblogs.com/justeene/p/4045567.html

你可能感兴趣的文章
Docker启动mysql的坑2
查看>>
j2ee爬坑行之二 servlet
查看>>
Python语言编程
查看>>
[poj 1469]Courses
查看>>
vue+element-ui实现表格checkbox单选
查看>>
测试开发学习进阶教程 视频&PDF
查看>>
C#基础-连接Access与SQL Server
查看>>
autofac
查看>>
MacOS 系统终端上传文件到 linux 服务器
查看>>
Excel导出POI
查看>>
兼容性
查看>>
自动执行sftp命令的脚本
查看>>
转 Merkle Tree(默克尔树)算法解析
查看>>
网络编程基础之socket编程
查看>>
各种浏览器的user-agent和
查看>>
Restful levels
查看>>
Phonegap移动开发:布局总结(一) 全局
查看>>
Java 变参函数的实现
查看>>
nrf51 SDK自带例程的解读
查看>>
SESSION技术
查看>>