A bare minimum web server for android platform

Download the source code of this article.

Since today’s mobile phone are having more computing power, running a web server on mobile phone can do lot more. There are lots of  Android Web Server applications out there that you can try. But I decided to create one my own.  We can create HTTP Server using org.apache.http packages, the only thing is that we could not run the server with default port, i.e. port 80. I think this is a Linux restriction and noting to do with Android platform.

To create a typical Web Server, first you want to create a server socket and listen to the desired port. Then accept the connection and finally process the HTTP request and send the response to the client.

To create a server socket we use the class java.net.ServerSocket. The constructor of this class accepts a port number to listen for the incoming connections. Once the ServerSocket object is created, we accept the incoming connection using ServerSocket.accept() method. This method is blocking so we create a separate thread to accept and process the incoming connections. The accept() method returns a java.net.Socket object which represents the accepted connection. Once the connection established, next we want to process the HTTP request. This can be done using org.apache.http.protocol.HttpService class. This class provides a minimal HTTP processor server side implementation. Following is the HttpService constructor:
HttpProcessor proc,
ConnectionReuseStrategy connStrategy,
HttpResponseFactory responseFactory)[/java]
This class is from the Apache implementation for Android. Explanation of Apache implementation is out of scope of this article. For more information about this please follow this link.

The first parameter org.apache.http.protocol.HttpProcessor is an interface that is used to process the requests and response. The class org.apache.http.protocol.BasicHttpProcessor is a default implementation of this interface.

The second parameter org.apache.http.ConnectionReuseStrategy determines the connection reuse strategy. There two different implementation of this interface; org.apache.http.impl.DefaultConnectionReuseStrategy and org.apache.http.impl.NoConnectionReuseStrategy. The first one re-uses the connection and the second one never re-use the connection. In normal cases we use the first one.

The HttpService class relies on the last parameter to process and send the HTTP response. org.apache.http.HttpResponseFactory is a factory interface that process and send the response to the client. The class org.apache.http.impl.DefaultHttpResponseFactory is a default implementation of this class.

To handle different HTTP requests, we use a handler map based on the URI pattern. For example for all the URIs which starts with /message will be handled by a class and URIs which starts with /dir will be handled by another class. For this purpose we use org.apache.http.protocol.HttpRequestHandlerRegistry class to create a map based on the URI pattern. This class implements org.apache.http.protocol.HttpRequestHandlerResolver which handles different request handlers. Using org.apache.http.protocol.HttpRequestHandlerRegistry we can register different URIs patterns and corresponding org.apache.http.protocol.HttpRequestHandler to handle the requests. HttpRequestHandler is a class that handles the HTTP request. We can create different HttpRequestHandler classes to handle HTTP requests that matches a particular pattern. To register a URI pattern we use the HttpRequestHandlerRegistry.register() method. The syntax of this method is:
[java]public void register (String pattern, HttpRequestHandler handler)[/java]
The first parameter is the URI pattern. This can be one of the following:

  • * – handles all requests
  • *<uri> – handles all requests that has <uri> at the end
  • <uri>* – handles all requests that starts with <uri>

The HttpService class will determine which handler should use based on the URI that is received. To handle the HTTP requests we use HttpService.handleRequest() method. The syntax of the method is:
[java]public void handleRequest (HttpServerConnection conn, HttpContext context)[/java]
The first parameter is org.apache.http.HttpServerConnection interface for use on the server side. We can us the org.apache.http.impl.DefaultHttpServerConnection class for this purpose which can be created by passing the Socket we received. Second parameter is an org.apache.http.protocol.HttpContext interface, again the org.apache.http.protocol.DefaultedHttpContext implementation can be used.

Sample Application

The sample application is a bare minimum web server. The server provided two functionality; send a message to the device and folder/file listing. To access the server we should know the IP address of the device, then we can use the URL http://<deviceip>:<port>. This will present the home page. This one provides you a very minimum functionality. I will be adding more functionality in future and will post the changes here.

You know, it’s very hard to explain a complicated subject in a short article like this. But I hope this gives an introduction to the web server implementation in Android.

34 Responses

  1. Sam March 5, 2011 / 6:30 pm

    Wow great tutorial. Thank you.

  2. Hugo Garcia-Cotte April 20, 2011 / 9:37 am

    Wonderful tutorial!
    Just passed from : Know nothing on http servers
    to : Know enough about http servers to do what I wanted to ^^

    Thanks !

  3. khushi May 22, 2011 / 5:41 am

    hi, this is very good tutorial. I am making somthing like this. file upload example like this. i create html file for file upload and use message handler class for that but i got only name of that files not content. pls help me. thanks

  4. Qamhan August 21, 2011 / 9:25 pm

    great !!!!!!!!!!!!
    it is a wonderful article and sample example.
    thanks allot

  5. Orijit September 27, 2011 / 9:33 am

    Very Nice tutorial. Simple words and a great example.

  6. Vycon October 21, 2011 / 1:41 am

    I am wondering if there is a way to implement an XML-RPC server based on this Http Server on Android.

  7. Andreu October 23, 2011 / 11:43 am

    Very good example, thank you very much. I have a question about it, how can I get POST requests and be able to read data sent by the client?

    • Robi June 12, 2015 / 7:23 am

      I also have this problem;

  8. Sparky October 30, 2011 / 11:24 am

    A great amount of information in a very short article. This has solved a problem I’ve been working on for a month or so – thanks. The only thing I’m having trouble with is getting it working with the emulator: The IP shown on the app in the AVD is, but when I hit this in a browser it results in a connection timeout. However, it works perfectly when I install it on the phone. Any ideas how to get it working via the emulator as well?

  9. yzw November 28, 2011 / 9:20 am

    a good article. I need a http server program for android system ,Not to support any dynamiclanguanges. Android on phone system is a little system. i-jetty is too lager and too smort for phone 。
    Hope you improve the stability and speed for aws ,that’s all perfect !

  10. Leon January 15, 2012 / 6:29 pm

    nice artice. i am also interested in getting the content of an POST request. is it possible to handle(receive) POST requests with your server?

  11. Leon January 15, 2012 / 7:30 pm

    oh, yes… it is.

    if (request instanceof HttpEntityEnclosingRequest) {
    HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
    if (entity != null) {
    Log.v(“AWS”, EntityUtils.toString(entity, “UTF-8”));

    … in the HttpRequestHandler does the trick. very nice!

  12. Thaylin February 9, 2012 / 7:05 pm

    I downloaded the code sample and it starts the server but I can’t seem to get the browser to connect on my device. I tossed a webview onto the main view and just pass it the url it outputs in the text when it sets all that but nothing. Am I missing something to this? I’ve tried even using that ipaddress with a path to items on my sdcard and still nothing. Your help would be awesome as this would help to solve a HUGE issue I’m having right now.

    Thanks in advance!

  13. predeeps February 27, 2012 / 12:53 pm

    i need to develop web application with android as server side. if possible kindly send some links or sample programs. thanks in advance…

  14. Aurel March 15, 2012 / 11:11 am

    A huge thank for sharing your knowledge ! 🙂

  15. Kirby March 19, 2012 / 9:17 pm

    Hi. This is a great tutorial. I’ve been trying to add SSL support for your example but still unable to do it. Do you have any tips or a quick tutorial on how to support SSL connectons?

    Thank you!

  16. dalal April 28, 2012 / 12:34 pm

    can i use this web server to get gps points from android and send them via bluetooth ?

    thank you

  17. pfcuttle May 8, 2012 / 3:26 pm

    Great code! I’m learning Java and the Android SDK at the same time, and your example is helping me a lot with my current project. Thanks!

    Now, on to serializing data with JSON.

  18. Praveen May 17, 2012 / 9:06 am

    Thanks for sharing your knowledge

  19. Kalyan August 15, 2012 / 6:43 pm

    Leon you are a life saver. I was looking for a way to get the posted parameters in my handle method for ages until I came across your site.I have linked your site, to question that I asked in stackoverflow.Thanks a bunch.

  20. Otis September 1, 2012 / 4:51 pm

    Hi, I want to handle a mutilple/fileupload. But I don’t know how to do it.
    I already get data-content in the boundary. But I can’t decode by GZIPInputStream.

  21. Solenoid September 13, 2012 / 10:59 pm

    An enormous thank you for this, I learned that a socket is, by far, not enough for HTML data to circulate.

  22. Yee December 16, 2012 / 6:25 am

    Thank you very much

  23. Raji March 15, 2013 / 9:02 am

    Thank you very much. Kindly give me some sample code to upload file.

  24. Zerho March 28, 2013 / 1:55 pm

    News about a further article? 🙂

  25. Ranjith June 28, 2013 / 6:28 am

    Based on this server, can i get the Request Payload data from HTTPRequest?

  26. Krish July 31, 2013 / 7:15 pm

    Thanks, looking for this for a long time.

  27. PC September 4, 2013 / 3:47 am

    Great article. Works great!! I’ve made simple file upload to work but not multipart file upload. Do you have any example for multipart file upload?

    • Edgar Villegas November 28, 2013 / 3:58 am

      It’s back again. Krishnaraj, please delete my original comment 🙂

  28. Alex March 7, 2014 / 1:45 am

    Brilliant! so thankful! the other solutions seemed so complicated…

  29. Akash Savairam December 17, 2015 / 4:01 pm

    Thank you so much for this tutorial.. This is really nicely written application. Thank you for sharing that much valueable information, explained with great simplicity. Amazing..!

Leave a Reply

Your email address will not be published. Required fields are marked *