netty 实现简单httpclient

代码参照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<FullHttpResponse> {

	@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<SocketChannel> {

	@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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值