博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
netty 实现简单httpclient
阅读量:6328 次
发布时间:2019-06-22

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

hot3.png

代码参照netty官网例子修改而成,保留最核心的部分

package com.rock.netty.http.t;import java.net.URI;import java.nio.charset.Charset;import io.netty.bootstrap.Bootstrap;import io.netty.channel.Channel;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.handler.codec.http.DefaultFullHttpRequest;import io.netty.handler.codec.http.FullHttpRequest;import io.netty.handler.codec.http.FullHttpResponse;import io.netty.handler.codec.http.HttpClientCodec;import io.netty.handler.codec.http.HttpContentDecompressor;import io.netty.handler.codec.http.HttpHeaderNames;import io.netty.handler.codec.http.HttpHeaderValues;import io.netty.handler.codec.http.HttpMethod;import io.netty.handler.codec.http.HttpObjectAggregator;import io.netty.handler.codec.http.HttpVersion;public class NettyHttpClientTest2 {		public static void main(String[] args) throws Exception {		sendRequest("http://www.baidu.com/");	}	private static void sendRequest(String url)throws Exception{		URI uri = new URI(url);		String host = uri.getHost();		int port = 80;		// Configure the client.		EventLoopGroup group = new NioEventLoopGroup();		Bootstrap b = new Bootstrap();		b.group(group).channel(NioSocketChannel.class).handler(new HttpClientInitializer());		// Make the connection attempt.		Channel ch = b.connect(host, port).sync().channel();		// Prepare the HTTP request.		FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());		request.headers().set(HttpHeaderNames.HOST, host);		request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);		request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);		// Send the HTTP request.		ch.writeAndFlush(request);		// Wait for the server to close the connection.		ch.closeFuture().sync();		// Shut down executor threads to exit.		group.shutdownGracefully();	}}class HttpClientMsgHandler extends SimpleChannelInboundHandler
{ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) throws Exception { if (!response.headers().isEmpty()) { for (CharSequence name : response.headers().names()) { for (CharSequence value : response.headers().getAll(name)) { System.err.println("HEADER: " + name + " = " + value); } } System.err.println(); } System.err.println(response.content().toString(Charset.forName("utf-8"))); }}class HttpClientInitializer extends ChannelInitializer
{ @Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec()); // Remove the following line if you don't want automatic content // decompression. p.addLast(new HttpContentDecompressor());//这里要添加解压,不然打印时会乱码 // Uncomment the following line if you don't want to handle // HttpContents. // p.addLast(new HttpObjectAggregator(1048576)); p.addLast(new HttpObjectAggregator(123433));//添加HttpObjectAggregator, HttpClientMsgHandler才会收到FullHttpResponse p.addLast(new HttpClientMsgHandler()); }}

 

转载于:https://my.oschina.net/rock117/blog/1475995

你可能感兴趣的文章
离屏canvas
查看>>
[Leetcode] Excel Sheet Column Title Number Conversion Excel列值转换
查看>>
Vue 组件库 HeyUI@1.16.0 更新日志
查看>>
互联网生态建设落地五大挑战——保险科技生态建设 ...
查看>>
进行短视频app开发工作时,可以加入它来保护青少年 ...
查看>>
Rxjs 学习推荐
查看>>
25G DAC无源高速线缆和25G光模块之间的区别
查看>>
乐乐茶完成近2亿元Pre-A轮融资,祥峰投资领投
查看>>
clickhouse修改时区
查看>>
CSS_定位
查看>>
第二十四章:页面导航(六)
查看>>
百度、长沙加码自动驾驶,湖南阿波罗智行科技公司成立 ...
查看>>
Java面试笔试题大汇总一(最全+详细答案)
查看>>
10 个 Linux 中方便的 Bash 别名
查看>>
[Server] 服务器配置SSH登录邮件通知
查看>>
程序员需要学数学吗?
查看>>
排序算法
查看>>
全新 DOCKER PALS 计划上线,带给您不一样的参会体验! ...
查看>>
如何用纯 CSS 创作一只愤怒小鸟中的黑炮
查看>>
胡玮炜卸任摩拜CEO,或将成为美团大裁员的开端
查看>>