Android中HttpServer怎么實現(xiàn)

Android中HttpServer怎么實現(xiàn),很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

創(chuàng)新互聯(lián)專注于高唐企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站建設(shè),商城網(wǎng)站建設(shè)。高唐網(wǎng)站建設(shè)公司,為高唐等地區(qū)提供建站服務(wù)。全流程按需網(wǎng)站策劃,專業(yè)設(shè)計,全程項目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)

1.NanoHttpd是BIO為底層封裝的框架,而AndroidAsync是NIO為底層封裝的,其他的是一樣的,而且其實AndroidAsync是仿照NanoHttpd框架寫的。所以,一定意義上來說,AndroidAsync是NanoHttpd的優(yōu)化版,當(dāng)然也要看具體應(yīng)用場景辣。

2.NanoHttpd只能用于HttpServer,但是AndroidAsync除了HttpServer的應(yīng)用還能用在webSocket、HttpClient等方面,其中從AndroidAsync中脫離出來的Ion的庫也是比較有名的。

3.NanoHttpd底層處理包含的返回狀態(tài)碼(例如: 200、300、400、500等)比較多;但是經(jīng)過筆者閱讀AndroidAsync的源碼發(fā)現(xiàn),AndroidAsync底層封裝返回的狀態(tài)碼只有兩種:200、404,正好筆者發(fā)現(xiàn)了這個坑(下面會講到,OPTIONS的例子)

下面看一下具體使用方法吧。

1.先說NanoHttpd:

因為NanoHttpd的框架實際就是一個單文件,可以直接去github上下載,下載地址

有了下載的文件,那么就可以繼承這個文件寫一個類,具體如下:

public class HttpServer extends NanoHTTPD {
  private static final String TAG = "HttpServer";

  public static final String DEFAULT_SHOW_PAGE = "index.html";
  public static final int DEFAULT_PORT = 9511;//此參數(shù)隨便定義,最好定義1024-65535;1-1024是系統(tǒng)常用端口,1024-65535是非系統(tǒng)端口

  public enum Status implements Response.IStatus {
    REQUEST_ERROR(500, "請求失敗"),
    REQUEST_ERROR_API(501, "無效的請求接口"),
    REQUEST_ERROR_CMD(502, "無效命令");

    private final int requestStatus;
    private final String description;

    Status(int requestStatus, String description) {
      this.requestStatus = requestStatus;
      this.description = description;
    }

    @Override
    public String getDescription() {
      return description;
    }

    @Override
    public int getRequestStatus() {
      return requestStatus;
    }
  }

  public HttpServer() {//初始化端口
    super(DEFAULT_PORT);
  }

  @Override
  public Response serve(IHTTPSession session) {
    String uri = session.getUri();
    Map<String, String> headers = session.getHeaders();

    //接收不到post參數(shù)的問題,       http://blog.csdn.net/obguy/article/details/53841559
    try {
      session.parseBody(new HashMap<String, String>());
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ResponseException e) {
      e.printStackTrace();
    }
    Map<String, String> parms = session.getParms();
    try {
      LogUtil.d(TAG, uri);

//判斷uri的合法性,自定義方法,這個是判斷是否是接口的方法
      if (checkUri(uri)) {
        // 針對的是接口的處理
        if (headers != null) {
          LogUtil.d(TAG, headers.toString());
        }
        if (parms != null) {
          LogUtil.d(TAG, parms.toString());
        }

        if (StringUtil.isEmpty(uri)) {
          throw new RuntimeException("無法獲取請求地址");
        }

        if (Method.OPTIONS.equals(session.getMethod())) {
          LogUtil.d(TAG, "OPTIONS探測性請求");
          return addHeaderResponse(Response.Status.OK);
        }

        switch (uri) {
          case "/test": {//接口2
            //此方法包括了封裝返回的接口請求數(shù)據(jù)和處理異常以及跨域
            return getXXX(parms);
          }
          default: {
            return addHeaderResponse(Status.REQUEST_ERROR_API);
          }
        }
      } else {
        //針對的是靜態(tài)資源的處理
        String filePath = getFilePath(uri); // 根據(jù)url獲取文件路徑

        if (filePath == null) {
          LogUtil.d(TAG, "sd卡沒有找到");
          return super.serve(session);
        }
        File file = new File(filePath);

        if (file != null && file.exists()) {
          LogUtil.d(TAG, "file path = " + file.getAbsolutePath());
//根據(jù)文件名返回mimeType: image/jpg, video/mp4, etc
          String mimeType = getMimeType(filePath); 

          Response res = null;
          InputStream is = new FileInputStream(file);
          res = newFixedLengthResponse(Response.Status.OK, mimeType, is, is.available());
//下面是跨域的參數(shù)(因為一般要和h6聯(lián)調(diào),所以最好設(shè)置一下)
          response.addHeader("Access-Control-Allow-Headers", allowHeaders);
          response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD");
          response.addHeader("Access-Control-Allow-Credentials", "true");
          response.addHeader("Access-Control-Allow-Origin", "*");
          response.addHeader("Access-Control-Max-Age", "" + 42 * 60 * 60);

          return res;
        } else {
          LogUtil.d(TAG, "file path = " + file.getAbsolutePath() + "的資源不存在");
        }

      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    //自己封裝的返回請求
    return addHeaderRespose(Status.REQUEST_ERROR);
  }

根據(jù)上面的例子,主要說以下幾點:

1)請求都能接收到,無論post還是get,或者是其他請求,如果需要過濾則自己去處理;

2)注意上面處理的接收不到post參數(shù)的問題,已經(jīng)給了參考鏈接在代碼注釋中,請查閱;

3)如果請求中既有接口又有靜態(tài)資源(例如html),那注意區(qū)分兩種請求,例如可以用uri去識別;當(dāng)然返回都可以用流的形式,都可以調(diào)用API方法newFixedLengthResponse();

4)筆者建議,最好處理一下跨域的問題,因為是Android有可能和h6聯(lián)調(diào),所以設(shè)置了跨域以后比較方便調(diào)試,當(dāng)然某些場景也可以忽略,看個人需求;方法已經(jīng)在以上代碼中寫了;

5)當(dāng)然最后最重要的一點肯定是開啟和關(guān)閉的代碼了:

/**
 * 開啟本地網(wǎng)頁點歌的服務(wù)
 */
public static void startLocalChooseMusicServer() {

  if (httpServer == null) {
    httpServer = new HttpServer();
  }

  try {
    // 啟動web服務(wù)
    if (!httpServer.isAlive()) {
      httpServer.start();
    }
    Log.i(TAG, "The server started.");
  } catch (Exception e) {
    httpServer.stop();
    Log.e(TAG, "The server could not start. e = " + e.toString());
  }

}

/**
 * 關(guān)閉本地服務(wù)
 */
public static void quitChooseMusicServer() {
  if (httpServer != null) {
    if (httpServer.isAlive()) {
      httpServer.stop();
      Log.d(TAG, "關(guān)閉局域網(wǎng)點歌的服務(wù)");
    }
  }
}

2再看一下AndroidAsync:

這個框架就比較有意思了,功能也多,本文直說HttpServer方面的相關(guān)知識,其余按下不表。

老規(guī)矩,先說用法:

在Gradle中加入:

dependencies {
  compile 'com.koushikdutta.async:androidasync:2.2.1'
}

代碼示例:(此處沒有處理跨域,如果需要的話,請根據(jù)上一個例子去處理)

public class NIOHttpServer implements HttpServerRequestCallback {

  private static final String TAG = "NIOHttpServer";

  private static NIOHttpServer mInstance;

  public static int PORT_LISTEN_DEFALT = 5000;

  AsyncHttpServer server = new AsyncHttpServer();

  public static NIOHttpServer getInstance() {
    if (mInstance == null) {
      // 增加類鎖,保證只初始化一次
      synchronized (NIOHttpServer.class) {
        if (mInstance == null) {
          mInstance = new NIOHttpServer();
        }
      }
    }
    return mInstance;
  }

//仿照nanohttpd的寫法
  public static enum Status {
    REQUEST_OK(200, "請求成功"),
    REQUEST_ERROR(500, "請求失敗"),
    REQUEST_ERROR_API(501, "無效的請求接口"),
    REQUEST_ERROR_CMD(502, "無效命令"),
    REQUEST_ERROR_DEVICEID(503, "不匹配的設(shè)備ID"),
    REQUEST_ERROR_ENV(504, "不匹配的服務(wù)環(huán)境");

    private final int requestStatus;
    private final String description;

    Status(int requestStatus, String description) {
      this.requestStatus = requestStatus;
      this.description = description;
    }

    public String getDescription() {
      return description;
    }

    public int getRequestStatus() {
      return requestStatus;
    }
  }

  /**
 * 開啟本地服務(wù)
 */
  public void startServer() {
//如果有其他的請求方式,例如下面一行代碼的寫法
    server.addAction("OPTIONS", "[\\d\\D]*", this);
    server.get("[\\d\\D]*", this);
    server.post("[\\d\\D]*", this);
    server.listen(PORT_LISTEN_DEFALT);
  }

  @Override
  public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
    Log.d(TAG, "進(jìn)來了,哈哈");
    String uri = request.getPath();
//這個是獲取header參數(shù)的地方,一定要謹(jǐn)記哦
    Multimap headers = request.getHeaders().getMultiMap();

    if (checkUri(uri)) {// 針對的是接口的處理
      //注意:這個地方是獲取post請求的參數(shù)的地方,一定要謹(jǐn)記哦
      Multimap parms = (( AsyncHttpRequestBody<Multimap>)request.getBody()).get();
      if (headers != null) {
        LogUtil.d(TAG, headers.toString());
      }
      if (parms != null) {
        LogUtil.d(TAG, "parms = " + parms.toString());
      }

      if (StringUtil.isEmpty(uri)) {
        throw new RuntimeException("無法獲取請求地址");
      }

      if ("OPTIONS".toLowerCase().equals(request.getMethod().toLowerCase())) {
        LogUtil.d(TAG, "OPTIONS探測性請求");
        addCORSHeaders(Status.REQUEST_OK, response);
        return;
      }

      switch (uri) {
          case "/test": {//接口2
            //此方法包括了封裝返回的接口請求數(shù)據(jù)和處理異常以及跨域
            return getXXX(parms);
          }
          default: {
            return addHeaderResponse(Status.REQUEST_ERROR_API);
          }
        }
    } else {
      // 針對的是靜態(tài)資源的處理
      String filePath = getFilePath(uri); // 根據(jù)url獲取文件路徑

      if (filePath == null) {
        LogUtil.d(TAG, "sd卡沒有找到");
        response.send("sd卡沒有找到");
        return;
      }
      File file = new File(filePath);

      if (file != null && file.exists()) {
        Log.d(TAG, "file path = " + file.getAbsolutePath());

        response.sendFile(file);//和nanohttpd不一樣的地方

      } else {
        Log.d(TAG, "file path = " + file.getAbsolutePath() + "的資源不存在");
      }
    }
  }
}

根據(jù)上面的例子,主要說以下幾點:{大概說的就是api用法啊這一類的}

1)例如:server.addAction("OPTIONS", "[\d\D]", this)是通用的過濾請求的方法。第一個參數(shù)是請求的方法,例如用“OPTIONS”、“DELETE”、“POST”、“GET”等(注意用大寫),第二個參數(shù)是過濾uri的正則表達(dá)式,此處是過濾所有的uri,第三個是回調(diào)參數(shù)。server.post("[\d\D]", this)、server.get("[\d\D]*", this)這個是上一個方法的特例。server.listen(PORT_LISTEN_DEFALT)這個是監(jiān)聽端口;

2) request.getHeaders().getMultiMap()這個是獲取header參數(shù)的地方,一定要謹(jǐn)記哦;

3)(( AsyncHttpRequestBody<Multimap>)request.getBody()).get()這個地方是獲取post請求的參數(shù)的地方;

4)獲取靜態(tài)資源的代碼是在回調(diào)方法onResponse的else中,例子如上。

5)說一下OPTIONS的坑點,因為AndroidAsync這個框架中封裝的返回http的狀態(tài)碼只有兩種,假如過濾方法中沒有包含例如OPTIONS的請求方法,實際上返回給客戶端的http狀態(tài)碼是400,而反映到瀏覽器的報錯信息竟然是跨域的問題,找了很久才找到,請注意。

總結(jié):

1)同一個頁面:

NanoHttpd耗時:1.4s

AndroidAsync耗時:1.4s

但是在第二次進(jìn)去的時候,AndroidAsync的耗時明顯比第一個少了,筆者猜測是因為AndroidAsync底層做了一些處理。

2)從api分析的話,NanoHttpd的用法比較方便,獲取傳遞的參數(shù)那些的api比較好用;AndroidAsync的api就相對來說要復(fù)雜一些,例如params的獲取。

3)從場景來分析的話,如果需要并發(fā)量高的需求,一定要用AndroidAsync;但是如果不需要的話,那就再具體分析。

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。

分享題目:Android中HttpServer怎么實現(xiàn)
文章轉(zhuǎn)載:http://bm7419.com/article48/pccihp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、云服務(wù)器關(guān)鍵詞優(yōu)化、網(wǎng)站改版、網(wǎng)站制作、Google

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

綿陽服務(wù)器托管