Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自建 Android Web 伺服器(三):HTTP 回應的處理

編輯:關於 Android 程式設計

上一篇完成了 HTTP 請求的監聽,接下來要回答:怎麼回應?實務上會遇到幾種典型情況。

  1. 請求方法不支援:例如服務端只實作了 GET/POST,卻收到 DELETE,回覆 501。
  2. 請求資源不存在:回覆 404 頁面。
  3. 請求型別不支援:檔案存在但副檔名未開放,回覆 404.7。
  4. 一切正常:把對應資源回傳給客戶端。
  5. 其他例外。

SessionThread.java:負責單一連線的往返

public class SessionThread extends Thread {
    private Socket _clientSocket = null;
    private final int BUFFER_MAX = 8192;
    private DataHandle _dataHandle = null;

    public SessionThread(Socket clientSocket) {
        this._clientSocket = clientSocket;
    }

    public void closeSocket() {
        if (_clientSocket == null) return;
        try {
            _clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            InputStream socketInput = _clientSocket.getInputStream();
            byte[] buffer = new byte[BUFFER_MAX];
            socketInput.read(buffer);
            _dataHandle = new DataHandle(buffer);
            byte[] content = _dataHandle.fetchContent();
            sendResponse(_clientSocket, content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendResponse(Socket clientSocket, byte[] content) throws IOException {
        OutputStream socketOut = clientSocket.getOutputStream();
        byte[] header = _dataHandle.fetchHeader(content.length);
        socketOut.write(header);
        socketOut.write(content);
        socketOut.close();
        clientSocket.close();
    }
}

重點:

  • 收到請求後,為每個連線建立一個 SessionThread(上一篇已說明)。
  • run() 中建立 DataHandle 負責資料處理。
  • 回應時先送 header、再送 content,這符合 HTTP 的協定結構。

DataHandle.java:決定回什麼

public class DataHandle {
    private String _receiveInfo = "";
    private HttpHeader _httpHeader = null;
    private String _encoding = "utf-8";
    private String _serverName = "Simple Web Server";
    private String _responseCode = "200 OK";
    private String _contentType = "text/html";

    public DataHandle(byte[] recieveData) throws UnsupportedEncodingException {
        this._receiveInfo = new String(recieveData, _encoding);
        _httpHeader = new HttpHeader(_receiveInfo);
    }

    public byte[] fetchContent() {
        if (!isSupportMethod()) return fetchNotSupportMethodBack();

        String filePath = fetchFilePath();
        if (!FileSp.isExist(filePath)) return fetchNotFoundBack();

        if (!isSupportExtension()) return fetchNotSupportFileBack();

        return fetchBackFromFile(filePath);
    }

    public byte[] fetchHeader(int contentLength) throws UnsupportedEncodingException {
        return ("HTTP/1.1 " + _responseCode + "\r\n"
                + "Server: " + _serverName + "\r\n"
                + "Content-Length: " + contentLength + "\r\n"
                + "Connection: close\r\n"
                + "Content-Type: " + _contentType + ";charset=" + _encoding + "\r\n\r\n")
                .getBytes(_encoding);
    }

    private boolean isSupportMethod() {
        String method = _httpHeader.getMethod();
        if (method == null || method.length() <= 0) return false;
        method = method.toUpperCase();
        return method.equals("GET") || method.equals("POST");
    }

    private boolean isSupportExtension() {
        String contentType = _httpHeader.getContentType();
        if (contentType == null || contentType.length() <= 0) return false;
        _contentType = contentType;
        return true;
    }

    private String fetchFilePath() {
        String root = Defaults.getRoot();
        String fileName = _httpHeader.getFileName();
        if (fileName.startsWith("/") || fileName.startsWith("\\")) {
            return root + fileName.substring(1);
        }
        return root + fileName;
    }

    private byte[] fetchBackFromFile(String filePath) {
        return FileSp.read(filePath);
    }

    // 以下為三種錯誤頁面的組裝,格式相同,僅狀態碼與說明不同
    private byte[] fetchNotSupportMethodBack() { /* 501 - Method Not Implemented */ }
    private byte[] fetchNotSupportFileBack()  { /* 404.7 - Type Not Support */ }
    private byte[] fetchNotFoundBack()        { /* 404 - Not Found */ }
}

流程回顧

  1. isSupportMethod 判斷方法是否支援,不支援則走 fetchNotSupportMethodBack。
  2. 檢查請求的資源是否存在,不存在則走 fetchNotFoundBack。
  3. isSupportExtension 判斷型別是否支援,不支援則走 fetchNotSupportFileBack。
  4. 三關都通過,才由 fetchBackFromFile 讀檔並回應。

完成回應之後,剩下就是把這些能力接到界面上做控制,下一篇再談。

轉載請註明出處:Android 版 Web 服務器實現(三)HTTP 回應

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved