1. 程式人生 > >Netty協議開發(HTTP)

Netty協議開發(HTTP)

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()));
    }


}