zoukankan      html  css  js  c++  java
  • netty笔记3-http客户端

    前面使用netty实现了http服务器,已经可以从浏览器进行访问,其实netty也可以实现http客户端,来访问netty实现的http服务器

    一、httpclient

    public class HttpClient {
        public void connect(String host, int port) throws Exception {
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                Bootstrap b = new Bootstrap();
                b.group(workerGroup);
                b.channel(NioSocketChannel.class);
                b.option(ChannelOption.SO_KEEPALIVE, true);
                b.handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
                        ch.pipeline().addLast(new HttpResponseDecoder());
                        // 客户端发送的是httpRequest,所以要使用HttpRequestEncoder进行编码
                        ch.pipeline().addLast(new HttpRequestEncoder());
                        ch.pipeline().addLast(new HttpClientHandler());
                    }
                });
                ChannelFuture f = b.connect(host, port).sync();
                URI uri = new URI("/test");
                String msg = "Are you ok?";
                DefaultFullHttpRequest request = new DefaultFullHttpRequest(
                        HttpVersion.HTTP_1_1, HttpMethod.POST, uri.toASCIIString(),
                        Unpooled.wrappedBuffer(msg.getBytes()));
                // 构建http请求
                request.headers().set(HttpHeaderNames.HOST, host);
                request.headers().set(HttpHeaderNames.CONNECTION,
                        HttpHeaderNames.CONNECTION);
                request.headers().set(HttpHeaderNames.CONTENT_LENGTH,
                        request.content().readableBytes());
                request.headers().set("messageType", "normal");
                request.headers().set("businessType", "testServerState");
                // 发送http请求
                f.channel().write(request);
                f.channel().flush();
                f.channel().closeFuture().sync();
            } finally {
                workerGroup.shutdownGracefully();
            }
        }
        public static void main(String[] args) throws Exception {
            HttpClient client = new HttpClient();
            client.connect("127.0.0.1", 8000);
        }
    }

    二、HttpClientHandler

    public class HttpClientHandler extends ChannelInboundHandlerAdapter {
        private ByteBufToBytes reader;
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg)
                throws Exception {
            if (msg instanceof HttpResponse) {
                HttpResponse response = (HttpResponse) msg;
                System.out.println("CONTENT_TYPE:"+ response.headers().get(HttpHeaderNames.CONTENT_TYPE));
                if (HttpUtil.isContentLengthSet(response)) {
                    reader = new ByteBufToBytes(
                            (int) HttpUtil.getContentLength(response));
                }
            }
            if (msg instanceof HttpContent) {
                HttpContent httpContent = (HttpContent) msg;
                ByteBuf content = httpContent.content();
                System.out.println(content);
                System.out.println(reader);
                reader.reading(content);
                content.release();
                if (reader.isEnd()) {
                    String resultStr = new String(reader.readFull());
                    System.out.println("Server said:" + resultStr);
                    ctx.close();
                }
            }
        }
    
    }

    三、工具类

    public class ByteBufToBytes {
        private ByteBuf temp;
        private boolean end = true;
        public ByteBufToBytes(int length) {
            temp = Unpooled.buffer(length);
        }
        public void reading(ByteBuf datas) {
            datas.readBytes(temp, datas.readableBytes());
            if (this.temp.writableBytes() != 0) {
                end = false;
            } else {
                end = true;
            }
        }
        public boolean isEnd() {
            return end;
        }
        public byte[] readFull() {
            if (end) {
                byte[] contentByte = new byte[this.temp.readableBytes()];
                this.temp.readBytes(contentByte);
                this.temp.release();
                return contentByte;
            } else {
                return null;
            }
        }
        public byte[] read(ByteBuf datas) {
            byte[] bytes = new byte[datas.readableBytes()];
            datas.readBytes(bytes);
            return bytes;
        }
    }

     转自:https://blog.csdn.net/wangshuang1631/article/details/73251180/

  • 相关阅读:
    getContentResolver()内容解析者查询联系人、插入联系人
    ContentProvider备份短信,以xml文件存储
    ContentProvider详解
    bindService初步了解
    Service之来电监听(失败的案例)
    Android帧动画
    AlertDialog之常见对话框(单选对话框、多选对话框、进度条对话框)
    BroadcastReceiver之(手动代码注册广播)屏幕锁屏、解锁监听、开机自启
    BroadcastReceiver之有序广播
    [FJOI2015]火星商店问题
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/14831171.html
Copyright © 2011-2022 走看看