1. 程式人生 > >移動端搭建Http Server(五)—— 實現URL路由模組

移動端搭建Http Server(五)—— 實現URL路由模組

在前面幾篇文章中已經實現了移動端Server的關鍵前兩步:監聽遠端連線解析HTTP Headers中的資料,本文將要設計一下路由規則

1.URL路由規則

簡單來講就是客戶端請求一個URL,伺服器分發給哪個服務來處理

移動端Server要實現兩個功能:

  • 讓其他裝置開啟APP中內建好的頁面
  • 接收其他裝置傳輸給APP的圖片

我們對這兩種行為定義路由規則:
/static/ :定義為下載檔案的訪問路徑
/imageupload/ :定義為上傳檔案的訪問路徑

2.實現思路

  • 獲取URL相對路徑
  • 定義IUriResourceHandler並註冊相應的方法
  • 遍歷Handler

3.獲取URL相對路徑

在onAcceptRemotePeer中獲取URL,只需要獲取頭資訊的第一行,很簡單

String resourceUri = StreamToolKit.readLine(in).split(" ")[1];
System.out.print("resourceUri is :" + resourceUri);

4.定義IUriResourceHandler並註冊相應的方法

public interface IUriResourceHandler {

    boolean accept(String uri);

    void  handle(String uri, HttpContext httpContext);

}

實現類ResourceInAssetsHandler處理下載請求

public class ResourceInAssetsHandler implements IUriResourceHandler {

    private  String mAcceptPrefix = "/static/";

    @Override
    public boolean accept(String uri) {
        return uri.startsWith(mAcceptPrefix);//以prefix結尾時返回true
    }

    @Override
    public
void handle(String uri, HttpContext httpContext) throws IOException { OutputStream os = httpContext.getUnderlySocket().getOutputStream(); PrintWriter writer = new PrintWriter(os); writer.println("HTTP/1.1 200 OK"); writer.println(); writer.println("from resource in assets handler"); writer.flush(); } }

實現類UploadImageHandler處理上傳請求

public class UploadImageHandler implements IUriResourceHandler {


    private  String mAcceptPrefix = "/upload_image/";

    @Override
    public boolean accept(String uri) {
        return uri.startsWith(mAcceptPrefix);//以prefix結尾時返回true
    }

    @Override
    public void handle(String uri, HttpContext httpContext) throws IOException {
        OutputStream os = httpContext.getUnderlySocket().getOutputStream();
        PrintWriter writer = new PrintWriter(os);
        writer.println("HTTP/1.1 200 OK");
        writer.println();//輸出\r\n
        writer.println("from upload image handler");
        writer.flush();
    }
}

在SimpleHttpServer中增加註冊Handler方法

public  void  registerResourceHandler(IUriResourceHandler handler){
        mResourceHandlers.add(handler);
    }

在MainActivity中註冊兩個Handler

mSimpleServer = new SimpleHttpServer(webConfig);
mSimpleServer.registerResourceHandler(new ResourceInAssetsHandler());
mSimpleServer.registerResourceHandler(new UploadImageHandler());
mSimpleServer.startAsync();

5.遍歷Handler

在onAcceptRemotePeer中while迴圈後增加對Handlers的遍歷

for (IUriResourceHandler handler : mResourceHandlers) {
    if (!handler.accept(resourceUri))
        continue;
    handler.handle(resourceUri, httpContext);
}

6.執行驗證

這裡寫圖片描述

這裡寫圖片描述