Netty协议开发(HTTP)

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37598011/article/details/83422909

HTTP是一个属于应用层的面向对象协议,由于其简捷、快速的方式,适用于分布式超媒体信息系统。

HTTP协议的URL

http://host[":"port][abs_path]

http表示通过HTTP协议来定位网络资源;host表示合法的Internet主机域名或者IP地址;port指定一个端口号,为空则使用默认端口80;abs_path指定请求资源的URI。

HTTP请求消息(HttpRequest)

HTTP请求消息通常有三部分组成:

  1. 1.HTTP请求行
  2. 2.HTTP消息头
  3. 3.HTTP请求正文

请求行以一个方法符开头,以空格分开,后面跟着请求的URI和协议的版本,格式为:Method Request-URI HTTP-Version CRLF

其中Method表示请求方法,Request-URI是一个统一资源标识符,HTTP-Version表示请求的HTTP协议版本,CRLF表示回车和 换行。

请求方法有多种,各方法的作用如下:

GET

请求获取由Request-URI所标识的资源

POST

在Request-URI所标识的资源后附加新的数据

HEAD

请求获取由Request-URI所标识的资源的响应消息报头

OPTIONS

请求查询服务器的性能,或查询与资源相关的选项和需求

PUT

请求服务器存储一个资源,并用Request-URI作为其标识

DELETE

请求服务器删除由Request-URI所标识的资源

TRACE

请求服务器回送收到的请求信息,主要用语测试或诊断

CONNECT 保留将来使用

GET和POST对的主要区别如下:

  1. 根据 HTTP 规范,GET 用于信息获取,而且应该是 安全的和幂等的;POST则表示可能改变服务器上的资源的请求。
  2. GET提交请求的数据会附在URL后面,以“?”分割URL和传输数据,多个参数用“&”连接;而POST提交会把提交的数据放置在HTTP消息的包体中,数据不会在地址栏中显示。
  3. 传输数据的大小不同,特定游览器对URL长度有限制,POST不是通过URL传值,理论上数据长度不会受限。
  4. 安全性。POST的安全性比GET的安全性高。


HTTP的部分请求头列表:

Content-Type

是返回消息中非常重要的内容,表示后面的文档属于什么MIME类型。Content-Type: [type]/[subtype]; parameter。例如最常见的就是text/html,它的意思是说返回的内容是文本类型,这个文本又是HTML格式的。原则上浏览器会根据Content-Type来决定如何显示返回的消息体内容

Host

指定请求资源的Intenet主机和端口号,必须表示请求url的原始服务器或网关的位置。HTTP/1.1请求必须包含主机头域,否则系统会以400状态码返回

Accept

浏览器可接受的MIME类型

Accept-Charset

浏览器可接受的字符集

Accept-Encoding

浏览器能够进行解码的数据编码方式,比如gzip。Servlet能够向支持gzip的浏览器返回经gzip编码的HTML页面。许多情形下这可以减少5到10倍的下载时间

Accept-Language

浏览器所希望的语言种类,当服务器能够提供一种以上的语言版本时要用到

Authorization

授权信息,通常出现在对服务器发送的WWW-Authenticate头的应答中

Connection

表示是否需要持久连接。如果Servlet看到这里的值为“Keep- Alive”,或者看到请求使用的是HTTP1.1(HTTP 1.1默认进行持久连接),它就可以利用持久连接的优点,当页面包含多个元素时(例如Applet,图片),显著地减少下载所需要的时间。要实现这一点,Servlet需要在应答中发送一个Content-Length头,最简单的实现方法是:先把内容写入 ByteArrayOutputStream,然后在正式写出内容之前计算它的大小

Content-Length

表示请求消息正文的长度

Cookie

这是最重要的请求头信息之一

From

请求发送者的email地址,由一些特殊的Web客户程序使用,浏览器不会用到它

Host

初始URL中的主机和端口

If-Modified-Since

只有当所请求的内容在指定的日期之后又经过修改才返回它,否则返回304“Not Modified”应答

Pragma

指定“no-cache”值表示服务器必须返回一个刷新后的文档,即使它是代理服务器而且已经有了页面的本地拷贝

Referer

包含一个URL,用户从该URL代表的页面出发访问当前请求的页面

User-Agent

浏览器类型,如果Servlet返回的内容与浏览器类型有关则该值非常有用

UA-Pixels,UA-Color,UA-OS,UA-CPU

由某些版本的IE浏览器所发送的非标准的请求头,表示屏幕大小、颜色深度、操作系统和CPU类型

 常见的MIME类型如下:

  •     text/html : HTML格式
  •     text/plain :纯文本格式      
  •     text/xml :  XML格式
  •     image/gif :gif图片格式    
  •     image/jpeg :jpg图片格式 
  •     image/png:png图片格式

以application开头的媒体格式类型:

  •    application/xhtml+xml :XHTML格式
  •    application/xml     : XML数据格式
  •    application/atom+xml  :Atom XML聚合格式    
  •    application/json    : JSON数据格式
  •    application/pdf       :pdf格式  
  •    application/msword  : Word文档格式
  •    application/octet-stream : 二进制流数据(如常见的文件下载)
  •    application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

还有一种常见的媒体格式是上传文件之时使用的:

  •     multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式

HTTP请求消息(HttpResponse)

HTTP响应也是由三个部分组成,分别是:状态行、消息报头、响应正文。

状态行的格式为:HTTP-Version Status-Code Reason-Phrase CRLF,其中HTTP-Version表示服务器HTTP协议的版本,Status-Code表示服务器返回的响应状态吗。

  1. - 1xx:   指示信息—表示请求已接收,继续处理。
  2. - 2xx:   成功—表示请求已经被成功接收、理解、接受。
  3. - 3xx:   重定向—要完成请求必须进行更进一步的操作。
  4. - 4xx:   客户端错误—请求有语法错误或请求无法实现。
  5. - 5xx: 服务器端错误—服务器未能实现合法的请求。

HTTP响应状态码和描述信息

状态码 状态描述
200   OK    客户端请求成功
400   Bad Request   由于客户端请求有语法错误,不能被服务器所理解。
400   Unauthonzed   请求未经授权。这个状态代码必须和WWW-Authenticate报头域一起使用
403    Unauthonzed   请求未经授权。这个状态代码必须和WWW-Authenticate报头域一起使用
404    Not Found   请求的资源不存在,例如,输入了错误的URL。
500   Internal Server Error 服务器发生不可预期的错误,导致无法完成客户端的请求。
503   Service Unavailable   服务器当前不能够处理客户端的请求,在一段时间之后,服务器可能会恢复正常

常用的响应报头:

名称 作用
Location Location响应报头域用于重定向接受者到一个新的位置。
Server Server响应报头域包含了服务器用来处理请求的软件信息。
WWW-Authenticate WWW-Authenticate响应报头域必须被包含在401(未授权的)响应消息中,这个报头域和前面讲到的Authorization请求报头域是 相关的,当客户端收到401响应消息,就要决定是否请求服务器对其进行验证。从这个响应报头域,可以知道服务器端对我们所请求的资源采用的是基本验证机制。
Content-Encoding Content-Encoding实体报头域被使用作媒体类型的修饰符,它的值指示了已经被应用到实体正文的附加内容编码,因而要获得Content- Type报头域中所引用的媒体类型,必须采用相应的解码机制。
Content-Language Content-Language实体报头域描述了资源所用的自然语言。
Content-Length Content-Length实体报头域用于指明正文的长度,以字节方式存储的十进制数字来表示,也就是一个数字字符占一个字节,用其对应的ASCII码存储传输。
Content-Type Content-Type实体报头域用语指明发送给接收者的实体正文的媒体类型。
Last-Modified Last-Modified实体报头域用于指示资源最后的修改日期及时间。
Expires Expires实体报头域给出响应过期的日期和时间。

实现一个简单的文件服务器:

package com.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 文件服务器
 */
public class HttpFileServer {
    // 这里目录要写完整的相对路径,包括main/java
    private static final String DEFAULT_URL = "/";

    public void run(final int port, final String url) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                    ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                    // 新增HTTP响应编码器,对HTTP响应消息进行编码
                    ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                    // 新增Chunked handler,主要作用是支持异步发送大的码流(例如大文件传输)
                    // 但是不占用过多的内存,防止发生java内存溢出错误
                    ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                    // HttpFileServerHandler用于文件服务器的业务逻辑处理
                    ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url));
                }
            });
            String host = "127.0.0.1";
            ChannelFuture future = b.bind(host, port).sync();
            System.out.println("HTTP文件目录服务器启动,网址是 : http://" + host + ":" + port + url);
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8081;
        String url = DEFAULT_URL;
        if (args.length > 1) url = args[1];
        new HttpFileServer().run(port, url);
    }
}

 重点是这块内容:

                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                    ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                    // 新增HTTP响应编码器,对HTTP响应消息进行编码
                    ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                    // 新增Chunked handler,主要作用是支持异步发送大的码流(例如大文件传输)
                    // 但是不占用过多的内存,防止发生java内存溢出错误
                    ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                    // HttpFileServerHandler用于文件服务器的业务逻辑处理
                    ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url));
                }

    首先向ChannelPipeline中添加HTTP请求消息解码器,随后添加了HttpObjectAggregator解码器,它将多个消息转换为单一的FullHttpRequest或者FullHttpResponse,原因是HTTP解码器在每个HTTP消息中会生成多个消息对象。然后新增HTTP响应编码器,对HTTP响应消息进行编码,然后新增Chunked handler,它的主要作用是支持异步发送大的码流,但不占用过多内存,防止Java发生内存溢出错误。最后添加HttpFileServerrHandler用于文件服务器的业务逻辑处理。

package com.netty.http;

import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive;
import static io.netty.handler.codec.http.HttpHeaders.setContentLength;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaders.Names.LOCATION;
import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static io.netty.handler.codec.http.HttpResponseStatus.FOUND;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelProgressiveFuture;
import io.netty.channel.ChannelProgressiveFutureListener;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.stream.ChunkedFile;
import io.netty.util.CharsetUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Pattern;
import javax.activation.MimetypesFileTypeMap;

/**
 * 返回的当前服务器下的文件目录
 */
public class HttpFileServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private final String url;

    public HttpFileServerHandler(String url) {
        this.url = url;
    }

    /**
     * DefaultFullHttpRequest, decodeResult: success)
     * GET /src/main/java/netty/ HTTP/1.1
     * Host: 127.0.0.1:8081
     * Connection: keep-alive
     * Cache-Control: max-age=0
     * User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
     * Upgrade-Insecure-Requests: 1
     * Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*;q=0.8
     * Accept-Encoding: gzip, deflate, br
     * Accept-Language: zh-CN,zh;q=0.9
     * Content-Length: 0
     * <p>
     * <p>
     * DefaultFullHttpRequest, decodeResult: success)
     * GET /favicon.ico HTTP/1.1
     * Host: 127.0.0.1:8081
     * Connection: keep-alive
     * Pragma: no-cache
     * Cache-Control: no-cache
     * User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36
     * Accept: image/webp,image/*,*;q=0.8
     * Referer: http://127.0.0.1:8081/src/main/java/netty/
     * Accept-Encoding: gzip, deflate, sdch, br
     * Accept-Language: zh-CN,zh;q=0.8
     * Content-Length: 0
     * <p>
     * 这里发现,每次刷新,或者点击都会有两个请求,很郁闷?
     * 浏览器每次发起请求,都会同时请求一次favicon.ico(本次不讨论浏览器缓存了favicon.ico)
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        // 过滤掉浏览器每次发起请求,都会同时请求一次favicon.ico
        if (request.getUri().equals("/favicon.ico")) {
            return;
        }
        System.out.println("服务器接受消息" + request);
        // 首先对HTTP请求小弟的解码结果进行判断,如果解码失败,直接构造HTTP 400错误返回。
        if (!request.getDecoderResult().isSuccess()) {
            sendError(ctx, BAD_REQUEST);
            return;
        }
        // 请求方法:如果不是从浏览器或者表单设置为get请求,构造http 405错误返回
        if (request.getMethod() != GET) {
            sendError(ctx, METHOD_NOT_ALLOWED);
            return;
        }
        // 对请求的的URL进行包装 final
        String uri = request.getUri();
        // 展开URL分析
        final String path = sanitizeUri(uri);
        if (path == null) {
            sendError(ctx, FORBIDDEN);
            return;
        }
        File file = new File(path);
        // 如果文件不存在或者是系统隐藏文件,则构造404 异常返回
        if (file.isHidden() || !file.exists()) {
            sendError(ctx, NOT_FOUND);
            return;
        }
        // 如果文件是目录,则发送目录的连接给客户端浏览器
        if (file.isDirectory()) {
            if (uri.endsWith("/")) {
                sendListing(ctx, file);
            } else {
                sendRedirect(ctx, uri + '/');
            }
            return;
        }
        // 用户在浏览器上第几超链接直接打开或者下载文件,合法性监测
        if (!file.isFile()) {
            sendError(ctx, FORBIDDEN);
            return;
        }
        // IE下才会打开文件,其他浏览器都是直接下载
        // 随机文件读写类以读的方式打开文件
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "r");
            // 以只读的方式打开文件
        } catch (FileNotFoundException fnfe) {
            sendError(ctx, NOT_FOUND);
            return;
        }
        // 获取文件长度,构建成功的http应答消息
        long fileLength = randomAccessFile.length();
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        setContentLength(response, fileLength);
        setContentTypeHeader(response, file);
        if (isKeepAlive(request)) {
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }
        ctx.write(response);
        ChannelFuture sendFileFuture;
        // 同过netty的村可多File对象直接将文件写入到发送缓冲区,最后为sendFileFeature增加GenericFeatureListener,
        // 如果发送完成,打印“Transfer complete”
        sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192), ctx.newProgressivePromise());
        sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
                if (total < 0) {
                    // total unknown
                    System.err.println("Transfer progress: " + progress);
                } else {
                    System.err.println("Transfer progress: " + progress + " / " + total);
                }
            }

            @Override
            public void operationComplete(ChannelProgressiveFuture future) throws Exception {
                System.out.println("Transfer complete.");
            }
        });
        ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        if (!isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            sendError(ctx, INTERNAL_SERVER_ERROR);
        }
    }

    private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");

    private String sanitizeUri(String uri) {
        try {
            // 使用JDK的URLDecoder进行解码
            uri = URLDecoder.decode(uri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            try {
                uri = URLDecoder.decode(uri, "ISO-8859-1");
            } catch (UnsupportedEncodingException e1) {
                throw new Error();
            }
        }
        // URL合法性判断
        if (!uri.startsWith(url)) {
            return null;
        }
        if (!uri.startsWith("/")) {
            return null;
        }
        // 将硬编码的文件路径
        uri = uri.replace('/', File.separatorChar);
        if (uri.contains(File.separator + '.') || uri.contains('.' + File.separator) || uri.startsWith(".") || uri.endsWith(".") || INSECURE_URI.matcher(uri).matches()) {
            return null;
        }
        return System.getProperty("user.dir") + File.separator + uri;
    }

    private static final Pattern ALLOWED_FILE_NAME = Pattern.compile("[A-Za-z0-9][-_A-Za-z0-9\\.]*");

    /**
     * 这里是构建了一个html页面返回给浏览器
     *
     * @param ctx
     * @param dir
     */
    private static void sendListing(ChannelHandlerContext ctx, File dir) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
        response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        StringBuilder buf = new StringBuilder();
        String dirPath = dir.getPath();
        buf.append("<!DOCTYPE html>\r\n");
        buf.append("<html><head><title>");
        buf.append(dirPath);
        buf.append(" 目录:");
        buf.append("</title></head><body>\r\n");
        buf.append("<h3>");
        buf.append(dirPath).append(" 目录:");
        buf.append("</h3>\r\n");
        buf.append("<ul>");
        // 此处打印了一个 .. 的链接 buf.append("<li>链接:<a href=\"../\">..</a></li>\r\n");
        // 用于展示根目录下的所有文件和文件夹,同时使用超链接标识
        for (File f : dir.listFiles()) {
            if (f.isHidden() || !f.canRead()) {
                continue;
            }
            String name = f.getName();
            if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
                continue;
            }
            buf.append("<li>链接:<a href=\"");
            buf.append(name);
            buf.append("\">");
            buf.append(name);
            buf.append("</a></li>\r\n");
        }
        buf.append("</ul></body></html>\r\n");
        ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
        response.content().writeBytes(buffer);
        buffer.release();
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
        response.headers().set(LOCATION, newUri);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void setContentTypeHeader(HttpResponse response, File file) {
        MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        response.headers().set(CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath()));
    }


}

猜你喜欢

转载自blog.csdn.net/qq_37598011/article/details/83422909