在Android中實現一個簡易的Http伺服器

來源:互聯網
上載者:User

標籤:server   ofo   為我   hashmap   處理   erro   請求   xtend   message   

最近遇到一個需求需要在App中建立一個Http伺服器供供瀏覽器調用,用了下開源的微型Htpp伺服器架構: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參數包含了請求的各種資訊,這裡顯示擷取了要求方法,因為我們的項目中暫時只用post(demo),所以只針對post請求做了處理,get的處理會更簡單。因為post請求中帶有body,所以需要先聲明一個HashMap,將body中的索引值對取出來。這裡我們把請求過來的json資料對應到了"postData",然後從通過"

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

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

在Android中實現一個簡易的Http伺服器

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.