Adding Library
We are assuming that you have already created your project. So lets skip that part. We are going add a library. Open your app level build.gradle
and add this line: implementation 'com.nanohttpd:nanohttpd-webserver:+'
and sync it.
Start/Stop Server
We have to create a class extending another class named NanoHTTPD
and then implement the serve method and override the Constructor. Here is the code:
import fi.iki.elonen.NanoHTTPD; public class LocalStreamingServer extends NanoHTTPD{ public LocalStreamingServer(int port){ super(port); } @Override public Response serve(IHTTPSession session){ String msg = "<html><body><h1>Hello server</h1>\n"; Map<String, String> parms = session.getParms(); if (parms.get("username") == null) { msg += "<form action='?' method='get'>\n <p>Your name: <input type='text' name='username'></p>\n" + "</form>\n"; } else { msg += "<p>Hello, " + parms.get("username") + "!</p>"; } return newFixedLengthResponse(msg + "</body></html>\n"); } }
LocalStreamingServer server = new LocalStreamingServer(4990); try{ server.start(); //Log.e("local", server.get + " asdf"); }catch(IOException e){ e.printStackTrace(); }
server.stop()
.After starting the server open browser in your phone and go to localhost:4990
there you will see some results. Congratulation, your done.