2

I have this web server class:

private class WebServer extends NanoHTTPD {

    public WebServer()
    {
        super(PORT);
        Log.i("myTag", "THIS IS RUNNING2");
    }

    @Override
    public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parameters, Map<String, String> files) {

        Log.i("myTag", "THIS IS RUNNING3");

        String answer = "";
        try {
            // Open file from SD Card
            File root = Environment.getExternalStorageDirectory();
            FileReader index = new FileReader(root.getAbsolutePath() + "/www/index.html");
            BufferedReader reader = new BufferedReader(index);

            String line = "";
            while ((line = reader.readLine()) != null) {
                answer += line;
            }
            reader.close();
        } catch(IOException ioe) {
            Log.w("httpd", answer);
        }

        return new NanoHTTPD.Response(answer);
    }
}

which I found online (http://devnote1.blogspot.com/2016/05/android-studio-nanohttpd.html). I followed the tutorial to a T.

I set 3 logs that should be visible in logcat under the tag, "myTag" and I notice the third log in the serve() method does not get outputted. In my android studio, the serve method has a line running through it and the tooltip says: "Overrides deprecated method in 'import fi.iki.elonen.NanoHTTPD'. Can anyone help me to get around this?

I am using this dependency:

compile 'com.nanohttpd:nanohttpd-webserver:2.1.1'

When I go into the browser and enter localhost:8080, it does not give me a 'site cannot be reached' error so I believe some web server stuff is working. Any help is appreciated. Thank you

Billy Kong
  • 31
  • 4

1 Answers1

0

The problem is with the permissions. You have to allow permissions at runtime: https://developer.android.com/training/permissions/requesting.html

If you just set it in the manifest, you will still get permissions denied.

 int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);

    if (permissionCheck == 0) {
        Log.i("perm", "granted");
    } else if (permissionCheck == -1){
        Log.i("perm", "denied");

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

    }

and you have to override this:

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    Log.i("perm", "request code = " + requestCode);

    if (requestCode == 1) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.i("perm", "GRANTED");
        }
    }
    return;
}
Billy Kong
  • 31
  • 4