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

Add the library to your build.gradle file.

AndroidManifest.xml

You need the internet permission to host the server

2) Usage

Extend the NanoHTTPD class

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

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.

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

JKAndroidWebserver

JKAndroidWebserver

Webserver HelloWorld

Webserver HelloWorld