Skip to main content

Handling multipart/form-data with NanoHTTPD

I am in the process of reviving an old project from 2014 that I never finished because of other work commitments. In that time, bitrot has set in, the Android API has moved on and all in all, the home-brewed HTTP server I wrote using SocketServer and the org.apache libraries had to go!

I looked around, found a couple of contenders and after much time decided to go with NanoHTTPD because it is lean, small and fits in exactly two files. The main server is in one file `NanoHTTPD.java`and there is another file called `ServerRunner.java` which manages instances of running servers.

The others

The other project I looked at is this one: https://github.com/koush/AndroidAsync
which led me a merry dance and I just couldn't figure out how get the POST data I had uploaded. I spent a few days really digging at it with Wire Shark too to make sure the data was going up. It was. Whatever... I had used it via a gradle dependency entry but I dropped it and went back to NanoHTTPD.

For me, NanoHTTPD is short, sharp and to the point. Whilst other offerings make it easy to set up URL routing with regex expressions and callbacks and things, NanoHTTPD leave all that down to you and your creativity! I prefer that anyway.

POST and multipart/form-data

With all the other things it does, NanoHTTPD does them well, offers simple but efficient helper functions here and there but the one thing it currently doesn't have is the ability to stream the incoming data to your application. Instead, it uploads the entire file into the local device, normally ending up somewhere under the `/sdcard/` folder. Typically it creates files like this, this is `adb shell` listing the `/sdcard` folder after uploading a simple JPEG image:
----rwxr-x system   sdcard_rw    38546 2016-06-03 13:32 NanoHTTPD--1954269476
Thankfully it also cleans up after it has finished... when your serve() method has completed, it will automatically delete any files that it creates which is quite handy!

Getting your data

So... here is my custom serve() function, I've posted the complete method. I've written my own handler factory code that gives back an instance of my ICmdHandler interface and that's why it is so short. In order to use NanoHTTPD you have to create a subclass of it and then override a single function like this:

  @Override
  public Response serve(IHTTPSession session) throws IOException, ResponseException
  {
    Map<String, String> fileList = null;
    Method method = session.getMethod();

    if (NanoHTTPD.Method.POST.equals(method) || NanoHTTPD.Method.PUT.equals(method)) {
      fileList = new HashMap<>();
      session.parseBody(fileList);
    }

    ICmdHandler handler = EmCmdBase.handlerFor(app, session, fileList);
    return handler.execute(session, this.app);
  }

Using the file data

Once you have called `session.parseBody()`, which could take a while according to the number and size of files uploaded, you can use the usual classes to read them. On return, `fileList` will contain one entry per uploaded file, the first entry is the name associated with the upload, for example, the following `curl` command:
curl -F stuff=@my_data.txt http://device_ip:port/<app-url>
...will result in a `multipart/form-data` uploaded to the device, and then `fileList` will be of size 1 and the key will be "file" and the value will be the unique name given to it by NanoHTTPD. Here is a variable expansion from AndroidStudio of a single uploaded file:


Remember that the default NanoHTTP file manager will these files for you.

So, there you go... a simple and effective way to get POST data using NanoHTTPD. It's a really really clever and nice project, please check it out!

NanoHTTPD GitHub page


Comments

Popular posts from this blog

AndroidStudio and a RAM Disk

Ok, my iMac is late 2012 and only has 8GB of RAM. I decided to see if it would be possible to speed up my development cycle, especially for running unit tests and the like but just as much for an improved build time as well. After much fiddling in the dark and reading some great pages, I eventually came up with the following solution that works for me but bear this in mind: Danger Will Robinson RAM is volatile so everything you do is gone forever when you unmount it or shutdown so don't forget to copy your changes elsewhere. If you have Git integrated properly then get into the habit of committing frequently. I have considered writing a small bash script to run `rsync` from a custom menu option  (and thus a shortcut key binding) or look into using the Apple Automator to transfer any changed files across to the hard drive. Whatever... you have been warned! Step one: Create the RAM disk, I do it like this: diskutil erasevolume HFS + "RAMBO" `hdiutil attac

Prime Peace

I think prime numbers are the numerical expression of peace. Restful nodes in the vibration of everything. Prime factorisation has always struck me as something truly astounding and it is reassuring to know that awsesome minds are hard at work trying to solve the Riemann hypothesis right now. There are some truly wonderful professional and amateur (in the nicest sense of the word) explorations I have watched recently and the ones that moved me the most, in order of cool factor were: This guy,Carlos Paris, has put in some serious work with AutoCAD and made some interesting observations. I truly enjoyed watching all of his four videos. Awesome work Carlos. As an interested amateur I found his work and thoughts to be very compelling. I am sure the professionals would groan or moan but to me this video is most excellent and informative. Speaking of the professionals, this video is also very interesting to watch as it goes some way to visually explaining the Riemann hypothesis in