How to create nanohttpd server in android?

JunHong picture JunHong · May 15, 2013 · Viewed 16.3k times · Source

Actually ,I had searched some questions and go to the github. But I'm new ,I cannot understand the example.

I want to create the http server in android so I can access it in PC browser.

I had instance a class extend nanohttpd, but the server just don't work. I don't know why ,my computer and phone are in the same WIFI,uh.....

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");
        };
    }

}

Answer

Paul Hawke picture Paul Hawke · May 21, 2013

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.