How to create nanohttpd server in android?

Actually, I searched for some questions and went to github. But I am a beginner, I can not understand an example.

I want to create an http server in android in order to access it in a PC browser.

I had an instance of a class extending nanohttpd, but the server just wasn't working. I don’t know why, my computer and phone are in the same WIFI that ...

public class MyHTTPD extends NanoHTTPD { /** * Constructs an HTTP server on given port. */ public MyHTTPD()throws IOException { super(8080); } @Override public Response serve( String uri, Method method, Map<String, String> header, Map<String, String> parms, Map<String, String> files ) { System.out.println( method + " '222" + uri + "' " ); String msg = "<html><body><h1>Hello server</h1>\n"; 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>"; msg += "</body></html>\n"; return new NanoHTTPD.Response(msg ); } public static void main( String[] args ) { try { new MyHTTPD(); } catch( IOException ioe ) { System.err.println( "Couldn't start server:\n" + ioe ); System.exit( -1 ); } System.out.println( "Listening on port 8080. Hit Enter to stop.\n" ); try { System.in.read(); } catch( Throwable t ) { System.out.println("read error"); }; } } 
+6
source share
4 answers

Your sample code is missing one small detail - you create a server, but you never call the start () method, which pushes it to listen for incoming connections. In your main () method you can write

  (new MyHTTPD()).start(); 

and everything will be fine, your server will react as you hoped.

The reason this works is twofold: I want the constructor to be a cheap, inexpensive operation, without side effects. For example, during unit testing, I call "start ()" in the setup and "stop ()" in the teardown methods of my jUnit test.

+10
source

This is the code that works for me, but I have another version of NANOHTTPD, I don’t have time to check your solution. Here is the UploadServer class and the Nano class. I am returning the upload.htm file from sdcard / Discover Control / Web path

 public class UploadServer extends NanoHTTPD { public UploadServer() throws IOException { super(8080, new File(".")); } public Response serve( String uri, String method, Properties header, Properties parms, Properties files ) { File rootsd = Environment.getExternalStorageDirectory(); File path = new File(rootsd.getAbsolutePath() + "/Discover Control/Web"); Response r = super.serveFile("/file-upload.htm", header, path, true); return r; } } 

Nanohttpd class

NanoHTTPD.java

FILE DOWNLOAD

file-upload.htm

Hope this helps and enjoy your work.

0
source

Android actions have a lifecycle and do not use the main() function.

If you want to start and stop the web server as part of the action, you need to start and stop the call in onPause and onResume , i.e.

 public class MyActivity extends Activity { private MyHTTPD mServer; @Override protected void onResume() { super.onResume(); try { mServer = new MyHTTPD(); mServer.start(); } catch (IOException e) { e.printStackTrace(); mServer = null; } @Override protected void onPause() { super.onPause(); if(mServer != null) { mServer.stop(); mServer = null; } } } 

An alternative is to implement a web server as part of the Service.

In the application in which I work, I have a requirement to keep the web server running, even if the user leaves the application. The only way to do this is to start and stop the web server as part of a long-term service that is not related to Activity. See Vogella for a great tutorial on Android services .

0
source

This code works to accurately view html pages with css class located in my assesst folders

 androidWebServer.start(); 

this will start the server under code for server functions

 public class AndroidWebServer extends NanoHTTPD { Realm realm; Map<String, String> parms; DBHelper db = new DBHelper(OpenRAP.getContext()); boolean isStartedHS = MainActivity.isStartedHS; private AsyncHttpServer server = new AsyncHttpServer(); private AsyncServer mAsyncServer = new AsyncServer(); private String TAG = "androidwebserver"; Storage storage = new Storage(OpenRAP.getContext()); public AndroidWebServer(int port) { super(port); } public AndroidWebServer(String hostname, int port) { super(hostname, port); } @Override public String getHostname() { return super.getHostname(); } @Override public Response serve(IHTTPSession session) { Method method = session.getMethod(); String uri = session.getUri(); Map<String, String> files = new HashMap<>(); SharedPreferences prefs = OpenRAP.getContext().getSharedPreferences(MainActivity.mypreference, MODE_PRIVATE); OpenRAP app = (OpenRAP) OpenRAP.getContext(); Storage storage = new Storage(OpenRAP.getContext()); String currentpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/"; String temp = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/temp/"; String ecarpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/ecars_files/"; String xcontent = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/xcontent/"; String Endpoint = session.getUri(); if (Endpoint.equals("/")) { String answer = ""; try { // Open file from SD Card File root = Environment.getExternalStorageDirectory().getAbsoluteFile(); FileReader index = new FileReader(root + "/www/openrap/index.html"); BufferedReader reader = new BufferedReader(index); String line = ""; while ((line = reader.readLine()) != null) { answer += line; } reader.close(); } catch (IOException ioe) { Log.w("Httpd", ioe.toString()); } return newFixedLengthResponse(answer); } 
0
source

Source: https://habr.com/ru/post/945052/


All Articles