Jens Klingenberg

How to run a WebServer on Android

Posted on July 27, 2017  •  2 minutes  • 299 words
Table of contents

So i have an old Samsung Galaxy S2. And i was thinking about things i could do with it. And i thought, maybe i can try to create a litte home automation server on it. First thing i was looking for was a way to run a WebServer on Android. For this a job i used the library NanoHttpd and i want to explain how you can use it too.

1) Setup

Build.gradle

dependencies {
  compile 'org.nanohttpd:nanohttpd:2.3.1'
}

Add the library to your build.gradle file.

AndroidManifest.xml

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

You need the internet permission to host the server

2) Usage

Extend the NanoHTTPD class

public class MyHTTPD extends NanoHTTPD {
    public static final int PORT = 8765;

    public MyHTTPD() throws IOException {
        super(PORT);
    }

    @Override
    public Response serve(IHTTPSession session) {
       String uri = session.getUri();

        if (uri.equals(&quot;/hello&quot;)) {
            String response = &quot;HelloWorld&quot;;
             return newFixedLengthResponse(response);
            }
        return  null;
        }
}

You can choose the network port in the constructor. Override the serve method to get the request and to create the response.

Return a file

@Override
    public Response serve(IHTTPSession session) {
       String uri = session.getUri();

        if (uri.equals(&quot;/hello&quot;)) {
          
         FileInputStream fis = new FileInputStream(YOUR_FILE);

         return newChunkedResponse(Response.Status.OK, MIME-Type, fis);
            }
        return  null;
        }

If you want to return a file, you have to generate a file input stream and set the MIME-Type of your file like “audio/mpeg”.

Start/Stop the server

Create a object of your server class and use the start/stop methods.

MyHTTPD   server = new MyHTTPD();
          server.start();
          server.stop();

Example App

I created to small example app for this. It shows the ip and the server port of your device and you can start/stop the server with the buttons. You can connect to your device ip:port/hello in your browser and it will return “Hello World”. You can find the project on my Github page

Screenshot


Screenshot

Let's connect: