Netty_使用http协议,post&get方式

来源:互联网 发布:苹果离线翻译软件 编辑:程序博客网 时间:2024/05/18 03:58
  1. jboss.netty中使用http协议的get请求方式较为简单, 但是post还是没有思路.
  2. io.netty中可以适用http协议实现post请求方式
post是属于安全的请求方式,不像get是明文的方式.
在 Java SDK 中有一个叫 JSSE(javax.net.ssl)包,这个包中提供了一些类来建立 SSL/TLS 连接。通过这些类,开发者就可以忽略复杂的协议建立流程,较为简单地在网络上建成安全的通讯通道。JSSE 包中主要包括以下一些部分:
  • 安全套接字(secure socket)和安全服务器端套接字

  • 非阻塞式 SSL/TLS 数据处理引擎(SSLEngine)

  • 套接字创建工厂 , 用来产生 SSL 套接字和服务器端套接字

  • 套接字上下文 , 用来保存用于创建和数据引擎处理过程中的信息

  • 符合 X.509 规范密码匙和安全管理接口
===========================netty服务代码===========================
packagecom.chis.backup;

importstaticio.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
importstaticio.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
importstaticio.netty.handler.codec.http.HttpHeaderNames.EXPIRES;
importstaticio.netty.handler.codec.http.HttpResponseStatus.OK;
importstaticio.netty.handler.codec.http.HttpVersion.HTTP_1_1;
importio.netty.buffer.ByteBuf;
importio.netty.buffer.Unpooled;
importio.netty.channel.Channel;
importio.netty.channel.ChannelHandlerAdapter;
importio.netty.channel.ChannelHandlerContext;
importio.netty.handler.codec.http.DefaultFullHttpResponse;
importio.netty.handler.codec.http.FullHttpResponse;
importio.netty.handler.codec.http.HttpContent;
importio.netty.handler.codec.http.HttpMethod;
importio.netty.handler.codec.http.HttpRequest;
importio.netty.handler.codec.http.HttpResponseStatus;
importio.netty.handler.codec.http.QueryStringDecoder;

importjava.io.BufferedInputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.UnsupportedEncodingException;
importjava.util.List;
importjava.util.Map;
importjava.util.Map.Entry;
importjava.util.regex.Pattern;

importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;

importcom.google.common.base.Charsets;

/**
 * 业务处理类
 *@authorChenZhenJian
 *
 */
publicclassHttpServerInboundHandlerextends  ChannelHandlerAdapter {

      privatestaticfinalLoggerLOGGER= LoggerFactory.getLogger(HttpServerInboundHandler.class);

//    private static final Pattern SEND_TASK_FOR_METHOD_GET_PATTERN = Pattern.compile("/dmap-sf/query(?:\\?.*)?");

//    private static final Pattern SEND_TASK_FOR_METHOD_POST_PATTERN = Pattern.compile("/dmap-sf/sendMsg(?:\\?.*)?");

      privateHttpRequestrequest;
      privatebooleanisGet;
      privatebooleanisPost;

      /**
       * POST: http://localhost:8844/dmap-sf/sendMsg?hello=df&world=women body: we
       * aretogather
       *
       * GET: http://localhost:8844/dmap-sf/query?hello=df&world=women
       */
      @Override
      publicvoidchannelRead(ChannelHandlerContext ctx, Object msg)throwsException {
            //1msg是HttpRequest
            if(msginstanceofHttpRequest) {
                  request= (HttpRequest) msg;
                  String uri =request.uri();
                  HttpMethod method =request.method();
                  isGet= method.equals(HttpMethod.GET);
                  isPost= method.equals(HttpMethod.POST);
                  System.out.println(String.format("Uri:%s method %s", uri, method));
                  //如果是get
//                if (SEND_TASK_FOR_METHOD_GET_PATTERN.matcher(uri).matches() && isGet) {
//                      System.out.println("doing something here.");
//                      Stringparam = "hello";
//                      Stringstr = getParamerByNameFromGET(param);
//                      System.out.println(param + ":" +str);
//                }
                  if( isGet) {
                        System.out.println("doing something here.");
                        String param ="hello";
                        String str = getParamerByNameFromGET(param);
                        System.out.println(param +":"+ str);
                  }
//                if (SEND_TASK_FOR_METHOD_POST_PATTERN.matcher(uri).matches() && isPost) {
//                      System.out.println("doing something here.");
//                }
                  if( isPost) {
                        System.out.println("doing something here.");
                  }
                  else{
                        String responseString ="返回的数据-------";
                        writeHttpResponse(responseString, ctx,OK);
                  }

            }

            //2msg是HttpContent
            if(! isGet) {
                  System.out.println("isPost");
                  if(msginstanceofHttpContent) {
                        HttpContent content = (HttpContent) msg;
                        ByteBuf buf = content.content();
                        String bodyString = buf.toString(Charsets.UTF_8);
                        System.out.println("body: "+ bodyString);
                        String l = getParamerByNameFromPOST("key", bodyString);
                        System.out.println("参数:"+l);
                        buf.release();
                        writeHttpResponse("post返回成功!", ctx,OK);
                  }
            }
      }

      @Override
      publicvoidchannelReadComplete(ChannelHandlerContext ctx)throwsException {
            ctx.flush();
      }

      @Override
      publicvoidexceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            LOGGER.error(cause.getMessage());
            ctx.close();
      }

      privateString getParamerByNameFromGET(String name) {
            QueryStringDecoder decoderQuery =newQueryStringDecoder(request.uri());
            returngetParameterByName(name, decoderQuery);
      }

      privateString getParamerByNameFromPOST(String name, String body) {
            QueryStringDecoder decoderQuery =newQueryStringDecoder("some?"+ body);
            returngetParameterByName(name, decoderQuery);
      }

      /**
       * 根据传入参数的key获取value
       *@paramname
       *@paramdecoderQuery
       *@return
       */
      privateString getParameterByName(String name, QueryStringDecoder decoderQuery) {
            Map<String, List<String>> uriAttributes = decoderQuery.parameters();
            for(Entry<String, List<String>> attr : uriAttributes.entrySet()) {
                  String key = attr.getKey();
                  for(String attrVal : attr.getValue()) {
                        if(key.equals(name)) {
                              returnattrVal;
                        }
                  }
            }
            returnnull;
      }
      privatevoidwriteHttpResponse(String responseString, ChannelHandlerContext ctx, HttpResponseStatus status)
                  throwsUnsupportedEncodingException {
            FullHttpResponse response =newDefaultFullHttpResponse(HTTP_1_1, OK);
            // 设置缓存大小
//          ByteBuffer byteBuffer = new ByteBuffer();
//          byteBuffer.size();
//          byteBuffer.append("恭喜你,成功了!");
            byte[] fileToByte =this.fileToByte("f://test.jpg");
            response.content().writeBytes(fileToByte);
            response.headers().set(CONTENT_TYPE,"image/png; charset=UTF-8");
            response.headers().setInt(CONTENT_LENGTH, response.content().writerIndex());
//          Channelch = ctx.channel();
//          ch.write(response);
            ctx.write(response);
            ctx.flush();
            ctx.close();
      }
      @SuppressWarnings("unused")
      privatevoidwriteHttpResponse1(String responseString, ChannelHandlerContext ctx, HttpResponseStatus status)
                  throwsUnsupportedEncodingException {
//          FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.wrappedBuffer(responseString
//                      .getBytes(Charsets.UTF_8)));
//          response.headers().set(CONTENT_TYPE, "text/json");
//          response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
//          response.headers().set(EXPIRES, 0);
//          if (HttpHeaders.isKeepAlive(request)) {
//                response.headers().set(CONNECTION, Values.KEEP_ALIVE);
//          }
            System.out.println("开始写入返回数据...");
            FullHttpResponse response =newDefaultFullHttpResponse(HTTP_1_1, status, Unpooled.wrappedBuffer(responseString
                        .getBytes(Charsets.UTF_8)));
//          response.content().writeBytes(responseString.getBytes());
            response.headers().set(CONTENT_TYPE,"text/html");
            response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
            response.headers().setInt(EXPIRES, 0);
//          if (HttpHeaders.isKeepAlive(request)) {
//                response.headers().set(CONNECTION, Values.KEEP_ALIVE);
//          }
            Channel ch = ctx.channel();
            ch.write(response);
//          ch.disconnect();
            ch.close();
//          ctx.write(response);
//          ctx.flush();
//          ctx.close();
      }
      
      /**
       * 本地图片的文件流
       *
       *@paramfilename   本地文件地址
       *@return
       */
      privatebyte[] fileToByte(String filename) {
            byte[] b =null;
            BufferedInputStream is =null;
            try{
                  System.out.println("开始>>>>"+ System.currentTimeMillis());
                  File file =newFile(filename);
                  b =newbyte[(int) file.length()];
                  is =newBufferedInputStream(newFileInputStream(file));
                  is.read(b);
            }catch(FileNotFoundException e) {
                  e.printStackTrace();
            }catch(IOException e) {
                  e.printStackTrace();
            }finally{
                  if(is !=null) {
                        try{
                              is.close();
                        }catch(IOException e) {
                              e.printStackTrace();
                        }
                  }
            }
            returnb;
      }

}


===================启动类====================
packagecom.chis.backup;

importio.netty.bootstrap.ServerBootstrap;
importio.netty.channel.ChannelFuture;
importio.netty.channel.ChannelInitializer;
importio.netty.channel.ChannelOption;
importio.netty.channel.EventLoopGroup;
importio.netty.channel.nio.NioEventLoopGroup;
importio.netty.channel.socket.SocketChannel;
importio.netty.channel.socket.nio.NioServerSocketChannel;
importio.netty.handler.codec.http.HttpRequestDecoder;
importio.netty.handler.codec.http.HttpResponseEncoder;
/**
 * netty_http启动类
 *@authorChenZhenJian
 *
 */
publicclassHttpServer { 
 
     
   publicvoidstart(intport)throwsException { 
        EventLoopGroup bossGroup =newNioEventLoopGroup(); 
        EventLoopGroup workerGroup =newNioEventLoopGroup(); 
       try
            ServerBootstrap b =newServerBootstrap(); 
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class
                    .childHandler(newChannelInitializer<SocketChannel>() { 
                               @Override 
                               publicvoidinitChannel(SocketChannel ch)throwsException { 
                                    ch.pipeline().addLast(newHttpResponseEncoder()); 
                                    ch.pipeline().addLast(newHttpRequestDecoder()); 
                                    ch.pipeline().addLast(newHttpServerInboundHandler()); 
                                } 
                            }).option(ChannelOption.SO_BACKLOG, 128)  
                    .childOption(ChannelOption.SO_KEEPALIVE,true); 
 
            ChannelFuture f = b.bind(port).sync(); 
 
            f.channel().closeFuture().sync(); 
        }finally
            workerGroup.shutdownGracefully(); 
            bossGroup.shutdownGracefully(); 
        } 
    } 
 
   publicstaticvoidmain(String[] args)throwsException { 
        HttpServer server =newHttpServer(); 
        System.out.println("Http Server listening on 10006 ...");
        server.start(10006); 
    } 
}
0 0