Recently encountered a need to create an HTTP server in the app for browser invocation, using the next open Source Micro HTPP Server framework: NANOHTTPD, Project address: https://github.com/NanoHttpd/nanohttpd
Directly on the code
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 CA N ' 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); }
Can be said to be very simple to use, the session parameter contains a variety of information requested, which shows that the request method is obtained, because our project is temporarily only post (demo), so only for the POST request processing, get processing will be more simple. Because the POST request has a body, it is necessary to declare a hashmap to take out the key-value pairs in the body. Here we map the requested JSON data to "PostData" and then from the "
Final String postdata = Files.get ("PostData");
This line of code takes it out. The session also has Getparams (), GetCookies (), Getheaders () and other methods, look at the name can know the function. At this point a simple HTTP server comes out, usually putting it in a service to wait for the request.
Implement a simple HTTP server in Android