欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何在Android中實現(xiàn)一個簡易的Http服務(wù)器

 更新時間:2018年05月24日 16:35:12   作者:why_rookie  
這篇文章主要介紹了如何在Android中實現(xiàn)一個簡易的Http服務(wù)器,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

最近遇到一個需求需要在App中創(chuàng)建一個Http服務(wù)器供供瀏覽器調(diào)用,用了下開源的微型Htpp服務(wù)器框架:NanoHttpd,項目地址:https://github.com/NanoHttpd/nanohttpd

直接上代碼

public class HttpServer extends NanoHTTPD {

  public HttpServer(int port) {
    super(port);
  }

  @Override
  public Response serve(IHTTPSession session) {

    HashMap<String, String> files = new HashMap<>();
    Method method = session.getMethod();

    if (Method.POST.equals(method)) {
      try {
        //notice:If the post with body data, it needs parses the body,or it can't get the body data;
        session.parseBody(files);
      }catch (IOException e) {
        return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT,
            "SERVER INTERNAL ERROR: IOException: " + e.getMessage());
      }catch (ResponseException e) {
        return newFixedLengthResponse(e.getStatus(), MIME_PLAINTEXT, e.getMessage());
      }
    }

    final String postData = files.get("postData");

    String transJson = Transmit.getInstance().getAuthoriseData(postData);

    return newFixedLengthResponse(transJson);
  }

使用起來可以說是很簡單了,session參數(shù)包含了請求的各種信息,這里顯示獲取了請求方法,因為我們的項目中暫時只用post(demo),所以只針對post請求做了處理,get的處理會更簡單。因為post請求中帶有body,所以需要先聲明一個HashMap,將body中的鍵值對取出來。這里我們把請求過來的json數(shù)據(jù)映射到了"postData",然后從通過"

final String postData = files.get("postData");

這行代碼將其取出來.session還有g(shù)etParams(),getCookies(),getHeaders()等方法,看名字就可以知道功能了。至此一個簡單的Http服務(wù)器就出來了,通常把它放在一個service中等待請求。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論