HTTP/HTTPS Proxy Server
直接上代码:HttpProxyServer
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* HTTP/HTTPS代理服务器
* 三个角色:真实客户端,代理客户端,目标主机
*
* 数据流向:
*
* ------->> 代理客户端 --------->>
* 真实客户端 目标主机
* <<-------- 代理客户端 <<--------
*
*/
public class HttpProxyServer {
int port;
public HttpProxyServer(int port) {
this.port = port;
}
public static void main(String[] args) throws Exception {
new HttpProxyServer(8443).run();
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.DEBUG),
new HttpProxyClientHandler());
}
})
.bind(port).sync().channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
/**
* 代理客户端去请求目标主机
*/
private static cla