本文来自阿钟的投稿,阅读大约10分钟
不得不感叹Netty的强大除了可以处理Socket的需求,竟然也还可以创建Web服务让Android充当一个Web服务器处理GET
、POST
等等请求….
一、创建Http服务
1public class HttpServer {
2 private static final String TAG = "HttpServer";
3 //服务开启在的端口
4 public static final int PORT = 7020;
5 public void startHttpServer() {
6 try {
7 EventLoopGroup bossGroup = new NioEventLoopGroup();
8 EventLoopGroup workerGroup = new NioEventLoopGroup();
9 ServerBootstrap b = new ServerBootstrap();
10 b.group(bossGroup, workerGroup)
11 .channel(NioServerSocketChannel.class)
12 .childHandler(new ChannelInitializer<SocketChannel>() {
13 @Override
14 protected void initChannel(SocketChannel socketChannel) throws Exception {
15 ChannelPipeline pipeline = socketChannel.pipeline();
16 // http服务器端对request解码
17 pipeline.addLast(new HttpRequestDecoder());
18 // http服务器端对response编码
19 pipeline.addLast(new HttpResponseEncoder());
20 // 在处理POST消息体时需要加上
21 pipeline.addLast(new HttpObjectAggregator(65536));
22 // 处理发起的请求
23 pipeline.addLast(new HttpServerHandler());
24 }
25 });
26 //绑定服务在7020端口上
27 b.bind(new InetSocketAddress(PORT)).sync();
28 Log.d(TAG, "HTTP服务启动成功 PORT=" + PORT);
29 } catch (Exception e) {
30 e.printStackTrace();
31 }
32 }
33}
启动HTTP服务
1new HttpServer().startHttpServer();
与我们之前写的连接Socket代码可以发现添加的
Decoder
、Encoder
不一致;这里是用的是Netty封装好的专门针对HTTP请求的解码器和编码器
运行的效果
null
二、在`HttpServerHandler`中处理收到的HTTP请求
1public class HttpServerHandler extends ChannelInboundHandlerAdapter {
2 private static final String TAG = "HttpServerHandler";
3 @Override
4 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
5 if (!(msg instanceo