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:

HttpService(
	HttpProcessor proc,
	ConnectionReuseStrategy connStrategy,
	HttpResponseFactory responseFactory)

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:

public void register (String pattern, HttpRequestHandler handler)

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:

public void handleRequest (HttpServerConnection conn, HttpContext context)

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.

32 Responses to “A bare minimum web server for android platform”

  1. Hugo Garcia-Cotte

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

    Thanks !

    Reply
  2. khushi

    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

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

    Reply
  4. 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?

    Reply
  5. 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 10.0.2.15:8080, 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?

    Reply
  6. 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 !

    Reply
  7. 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?

    Reply
  8. oh, yes… it is.

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

    … in the HttpRequestHandler does the trick. very nice!

    Reply
  9. 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!

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

    Reply
  11. 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!

    Reply
  12. hi,
    can i use this web server to get gps points from android and send them via bluetooth ?

    thank you

    Reply
  13. pfcuttle

    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.

    Reply
  14. 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.

    Reply
  15. 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.

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

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

    Reply
  18. Ranjith

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

    Reply
  19. 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?

    Reply
  20. Brilliant! so thankful! the other solutions seemed so complicated…

    Reply

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>