by piotrpolak

piotrpolak /android-http-server

A complete zero-dependency implementation of a web server and a servlet container in Java with a sam...

144 Stars 47 Forks Last release: Not found GNU General Public License v3.0 498 Commits 0 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:

Android HTTP Server

Small but powerful multithreaded web server written completely in Java SE and then ported to Android.

Build Status codecov Codacy Badge

The server implements most of the HTTP 1.1 specification and provides custom servlet API that can be used to handle dynamic pages. The servlet API is designed after the official

API yet it is not compatible. Dynamic pages support cookies, sessions, file uploads and anything else to build a common web application.

Key features

  • Small footprint, requires no external libraries
  • Handles HTTP requests in separate threads
  • Provides custom servlets API for generating dynamic content
  • Supports GET, POST, HEAD methods (or more, depending on the configuration)
  • Supports chunked transfer type
  • Provides full support for mime types (uses Apache like mime.type)
  • Supports buffered file upload (multipart requests), cookies, persisted sessions
  • Supports serving partial body (ranges)
  • Can serve static content both from file system and APK resources

Building the application

The provided Gradle wrapper should be used to build the application:

./gradlew clean build

Installing Android SDK from command line

When running the full build for the first time you must first install the Android SDK. You might either install it manually or use the following script that downloads and installs all required dependencies to


To make things work after you logout and login back, configure the

environment variable:
echo "export ANDROID_HOME=~/android-sdk" >> ~/.bashrc && source ~/.bashrc

The http subproject and the idea behind it

The http subproject is the heart of the application and it is independent on Android platform.

In fact the Android app was just an attempt to find a more practical use of the experimental HTTP protocol implementation.

One of the design goals was to keep the resulting artifact small in size and minimalistic in terms of dependency on other libraries - it does not require any third party component, all HTTP protocol implementation is based on parsing data read from raw TCP sockets.

Once the ro.polak.http package is mature enough it will be released as an independent artifact.

The subproject can be tested in the following way:

./gradlew :http:clean :http:check -PskipAndroidBuild

The original package code has been refactored and covered with unit and integration tests. Code coverage should be kept above 90%.


Android SDK compatibility issues

All application code is targeted to Java 7. It also compiles for Android SDK versions < 19 (try with resources is not supported, use IOUtilities.closeSilently(closeable) in a

block as an alternative when closing streams).

Another compatibility constraint is that

instead of
is used for generating random sequences in StringUtilities

Mutation testing

Mutation tests can be run by executing the following command:

./gradlew :http:clean :http:pitest -PskipAndroidBuild

The results can then be found under


Running standalone server (CLI)

Standalone server can be used to bundle the

subproject into a runnable server implementation. The CLI subproject is also independent on the Android platform, it is not bundled with the main APK.
./gradlew :cli:bootRun -PskipAndroidBuild

It is also possible to build one "uber-jar" and to use it as a standalone application:

./gradlew :cli:fatJar -PskipAndroidBuild

The resulting artifact can then be grabbed from


The standalone server jar can be run on any machine with the following command:

java -jar ./cli/build/libs/cli-all.jar

Overwriting configuration values from command line

java -jar ./cli/build/libs/cli-all.jar \
    -Dserver.port=8888 \

For a complete list of available parameters refer to

Command line interface0


A demo application is automatically deployed to Heroku and can be reached at:

Please note the deployed application does not contain the admin application since that is only available for Android. See Procfile for the deployment description.

Sample code

Hello World servlet

package example;

import ro.polak.http.servlet.HttpServletRequest; import ro.polak.http.servlet.HttpServletResponse; import ro.polak.http.servlet.HttpServlet;

public class HelloWorld extends HttpServlet {

public void service(HttpServletRequest request, HttpServletResponse response) {
    response.getWriter().print("Hello World!");


Request logging filter

package example;


import ro.polak.http.exception.ServletException; import ro.polak.http.servlet.Filter; import ro.polak.http.servlet.FilterChain; import ro.polak.http.servlet.FilterConfig; import ro.polak.http.servlet.HttpServletRequest; import ro.polak.http.servlet.HttpServletResponse;

public class RequestLoggingFilter implements Filter {

private static final Logger LOGGER = Logger.getLogger(RequestLoggingFilter.class.getName());

public void init(FilterConfig filterConfig) throws ServletException {
    // Do nothing

public void doFilter(HttpServletRequest request, HttpServletResponse response,
                     FilterChain filterChain) throws IOException, ServletException {

    LOGGER.fine("Handling incoming request " + request.getRequestURL());

    filterChain.doFilter(request, response);


Example servlets can be found in http/src/main/java/example.

A practical use of filters can be checked at and of the admin application.

Building a deployment descriptor

DeploymentDescriptorBuilder is an API alternative to traditional

approach that aims to make servlet mapping building and filter registration easy. See example code below.
package example;

import java.util.List; import java.util.regex.Pattern;

import ro.polak.http.configuration.DeploymentDescriptorBuilder; import ro.polak.http.configuration.ServerConfig; import;

class DeploymentDescriptorFactory { public List buildDeploymentDescriptor(SessionStorage sessionStorage, ServerConfig serverConfig) {

    return DeploymentDescriptorBuilder.create()


Serving static contents

Serving static resources is implemented using DefaultServlet - the servlet is automatically registered as the very last element of DeploymentDescriptorBuilder acting as a fallback resource.

The actual resource loading is implemented by registering an instance ResourceProvider in the server config.

Currently there are two resource providers implemented

Sample dummy implementation of a ResourceProvider

package ro.polak.http.resource.provider;

import ro.polak.http.servlet.impl.HttpServletRequestImpl; import ro.polak.http.servlet.impl.HttpServletResponseImpl;


public class DummyResourceProvider implements ResourceProvider {

 * Tells whether this resource provider can load resource for given path.
public boolean canLoad(final String path) {
    return false; // TODO Add some logic

 * Loads the resource for the given path by copying the stream to the response.getOutputStream().
public void load(final String path,
                 final HttpServletRequestImpl request,
                 final HttpServletResponseImpl response) throws IOException {

    // TODO Load the stream to response.getOutputStream();

 * Shuts down the resource provider if necessary, usually closes all open resources.
public void shutdown() {


Templating support

The following example presents how to integrate Jtwig templating engine.

First you need to add Jtwig dependency in your gradle file:

// ...
dependencies {
    // ...
    compile 'org.jtwig:jtwig-core:5.87.0.RELEASE'
// ...

Then it works out of the box:

package example;

import org.jtwig.JtwigModel; import org.jtwig.JtwigTemplate;

import ro.polak.http.exception.ServletException; import ro.polak.http.servlet.HttpServlet; import ro.polak.http.servlet.HttpServletRequest; import ro.polak.http.servlet.HttpServletResponse;

public class Templating extends HttpServlet {

public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
    JtwigTemplate template = JtwigTemplate.inlineTemplate("Hello {{ var }}");
    JtwigModel model = JtwigModel.newModel().with("var", "World");

    template.render(model, response.getOutputStream());



Admin main activity HTTP back-office login HTTP back-office menu

HTTP back-office drive access HTTP back-office server statistics HTTP back-office SMS inbox

500 error page trace in browser

Servlet error 500

Sample script to send SMS using wget command line utility

If you want to send a real SMS please remove "&test=1" from the POST params.

    echo "Phone number:"; read TO; echo "Message:"; read MESSAGE; \
    wget -qO- --post-data "to=$TO&message=$MESSAGE&test=1" \


Android HTTP server uses icons from the beautifully designed "Farm-Fresh Web Icons" pack by FatCow Web Hosting! These icon sets are licensed under a Creative Commons Attribution 3.0 License.


The project is shared upon GNU GPLv3 license.

If you are interested in a dedicated commercial license please drop me a line at

piotr [at] polak [dot] ro

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.