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
1 2 3 |
dependencies { compile 'org.nanohttpd:nanohttpd:2.3.1' } |
Add the library to your build.gradle file.
AndroidManifest.xml
1 |
<uses-permission android:name="android.permission.INTERNET"></uses-permission> |
You need the internet permission to host the server
2) Usage
Extend the NanoHTTPD class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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("/hello")) { String response = "HelloWorld"; 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
1 2 3 4 5 6 7 8 9 10 11 12 |
@Override public Response serve(IHTTPSession session) { String uri = session.getUri(); if (uri.equals("/hello")) { 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.
1 2 3 |
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
October 18, 2017 at 5:30 pm
Hello Jens Klingenberg,
have you ever migrated from Nanohttpd on Android to Nanohttpd on Linux?
Best regard
Nguyen
October 18, 2017 at 8:51 pm
Hi Nguyen,
i’m not sure what you mean with “Nanohttpd on linux”. Do you mean a usual java project? If so, there is a sample in the NanoHtttpd repository https://github.com/NanoHttpd/nanohttpd/tree/master/samples