在前面幾篇文章中已經實現了移動端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.運行驗證
在瀏覽器中輸入http://192.168.1.104:8088/static/1
http://192.168.1.104:8088/upload_image/1
這篇就到這裏結束了,最後還是附上github源碼地址:
https://github.com/jianiuqi/AndroidServer