How to create a HTTP server in Android?


Android Problem Overview

I would like to create a simple HTTP server in Android for serving some content to a client.

Any advice on how to build the server or use any existing library?

Android Solutions

Solution 1 - Android

Consider this one: <>;. Very small, written in Java. I used it without any problem.

Solution 2 - Android

NanoHttpd works like a charm on Android -- we have code in production, in users hands, that's built on it.

The license absolutely allows commercial use of NanoHttpd, without any "viral" implications.

Solution 3 - Android

This can be done using ServerSocket, same as on JavaSE. This class is available on Android. android.permission.INTERNET is required.

The only more tricky part, you need a separate thread wait on the ServerSocket, servicing sub-sockets that come from its accept method. You also need to stop and resume this thread as needed. The simplest approach seems to kill the waiting thread by closing the ServerSocket. If you only need a server while your activity is on the top, starting and stopping ServerSocket thread can be rather elegantly tied to the activity life cycle methods. Also, if the server has multiple users, it may be good to service requests in the forked threads. If there is only one user, this may not be necessary.

If you need to tell the user on which IP is the server listening,use NetworkInterface.getNetworkInterfaces(), this question may tell extra tricks.

Finally, here there is possibly the complete minimal Android server that is very short, simple and may be easier to understand than finished end user applications, recommended in other answers.

Solution 4 - Android

Another server you can try, actually it already provides Android enabled version.

Solution 5 - Android

You can try Restlet edition for android:

The source can be downloaded from Restlet website:

Solution 6 - Android

If you are using kotlin,consider these library. It's build for kotlin language.

AndroidHttpServer is a simple demo using ServerSocket to handle http request

AndroidHttpServer is very small , but the feature is less as well.

Ktor is a very nice library,and the usage is simple too


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbiquilloView Question on Stackoverflow
Solution 1 - AndroidKonstantin MilyutinView Answer on Stackoverflow
Solution 2 - AndroidPaul HawkeView Answer on Stackoverflow
Solution 3 - AndroidAudrius MeŇ°kauskasView Answer on Stackoverflow
Solution 4 - AndroidDmitriy RView Answer on Stackoverflow
Solution 5 - AndroidBharathView Answer on Stackoverflow
Solution 6 - Androidsteven chanView Answer on Stackoverflow