最近遇到一個需求須要在App中建立一個Http服務器供供瀏覽器調用,用了下開源的微型Htpp服務器框架:NanoHttpd,項目地址:https://github.com/NanoHttpd/...java
直接上代碼git
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",而後從經過"github
final String postData = files.get("postData");
這行代碼將其取出來.session還有getParams(),getCookies(),getHeaders()等方法,看名字就能夠知道功能了。至此一個簡單的Http服務器就出來了,一般把它放在一個service中等待請求。json