How to create nanohttpd server in android?

你说的曾经没有我的故事 提交于 2019-12-03 07:35:08

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

        (new MyHTTPD()).start();

and all would be well, your server would respond the way you hoped it would.

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

This is the code working for me, but I have different version of NANOHTTPD, I don't have time right now to test out your solution. Here is UploadServer class and Nano class. I return file-upload.htm 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 UPLOAD

file-upload.htm

Hope this helps and enjoy your work.

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

If you want to start and stop the webserver as part of the Activity then you need call start and stop in onPause and onResume, ie

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 the webserver as part of a Service.

In an app I'm working I have a requirement to keep the webserver running even if the user leaves the app. The only way to do this is to start and stop the webserver as part of a long-running Service that is not bound to the Activity. See Vogella's great tutorial on Android Services.

This code working for fine viewing html pages with css class which are in my assesst folders

androidWebServer.start();

this will start the server below 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);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!