Zwade Zwade - 1 year ago 555
Android Question

Using NanoHTTPD in Android

I am trying to use NanoHTTP to serve up an HTML file. However, NanoHTTP is relatively un-documented, and I am new to Android. My question is, where do I store the html file, and how specifically can I serve it up using NanoHTTP.

Answer Source

A late answer but may be useful to others.

Here is a simple hello Web Server, not exactly what you ask, but you can continue from here. The following program supposes you have a www directory in the root of the SD Card and a file index.html inside.

Main activity

package com.inforscience.web;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import java.util.*;

public class Httpd extends Activity
    private WebServer server;
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState)
        server = new WebServer();
        try {
        } catch(IOException ioe) {
            Log.w("Httpd", "The server could not start.");
        Log.w("Httpd", "Web server initialized.");

    // DON'T FORGET to stop the server
    public void onDestroy()
        if (server != null)

    private class WebServer extends NanoHTTPD {

        public WebServer()

        public Response serve(String uri, Method method, 
                              Map<String, String> header,
                              Map<String, String> parameters,
                              Map<String, String> files) {
            String answer = "";
            try {
                // Open file from SD Card
                File root = Environment.getExternalStorageDirectory();
                FileReader index = new FileReader(root.getAbsolutePath() +
                BufferedReader reader = new BufferedReader(index);
                String line = "";
                while ((line = reader.readLine()) != null) {
                    answer += line;

            } catch(IOException ioe) {
                Log.w("Httpd", ioe.toString());

            return new NanoHTTPD.Response(answer);


Obviously the NanoHTTPD class must be in the same package.

You need to grant internet permission in AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" />

EDIT: To access the server open you web browser with the IP of your device, e.g.