A bare minimum web server for android platform

by Krishnaraj Varma on December 26, 2010

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.

{ 18 comments… read them below or add one }

Sam March 5, 2011 at 6:30 pm

Wow great tutorial. Thank you.

Reply

Hugo Garcia-Cotte April 20, 2011 at 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 !

Reply

khushi May 22, 2011 at 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

Reply

Qamhan August 21, 2011 at 9:25 pm

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

Reply

Orijit September 27, 2011 at 9:33 am

Very Nice tutorial. Simple words and a great example.

Reply

Vycon October 21, 2011 at 1:41 am

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

Reply

Andreu October 23, 2011 at 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?

Reply

Sparky October 30, 2011 at 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 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

yzw November 28, 2011 at 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 !

Reply

Leon January 15, 2012 at 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?

Reply

Leon January 15, 2012 at 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″));
entity.consumeContent();
}
}
—————————————–

… in the HttpRequestHandler does the trick. very nice!

Reply

Thaylin February 9, 2012 at 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!

Reply

predeeps February 27, 2012 at 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…

Reply

Aurel March 15, 2012 at 11:11 am

A huge thank for sharing your knowledge ! :)

Reply

Kirby March 19, 2012 at 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!

Reply

dalal April 28, 2012 at 12:34 pm

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

thank you

Reply

pfcuttle May 8, 2012 at 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.

Reply

Praveen May 17, 2012 at 9:06 am

Thanks for sharing your knowledge

Reply

Leave a Comment

 

{ 1 trackback }

Previous post:

Next post: