working example of nanohttpd in android studio

user3197004 picture user3197004 · Sep 29, 2015 · Viewed 7.4k times · Source

I have been trying to get an simple nanohttpd server running but I cant figure out how to set it up.. I have tried to follow this guide: Using NanoHTTPD in Android tried the first answer but I get an error on this line: "private WebServer server;" "cannot resolve symbol 'WebServer'"

also tried following this: https://github.com/NanoHttpd/nanohttpd/wiki/How-to-use-NanoHttpd another error on this line: "return newFixedLengthResponse(sb.toString());" "error 'newFixedLengthResponse cannot be resolved."

I tried just adding the nanohttpd.class as well as importing nanohttpd.jar but neither seem to make a difference.

Does anyone know of a simple 'hello world' guide to nanohttpd that actually works? Or maybe a more documented simple web server for android?

Answer

GreyBeardedGeek picture GreyBeardedGeek · Sep 29, 2015

Here's code from a fairly simple app that I wrote using NanoHTTPD. It's called 'ClockServer' because I use it in a digital clock app, to allow the the clock's digit color, background color, and brightness to be set remotely.

I instantiate the ClockServer class in my app's Application subclass. As you can see, the serve method returns it's result like so:

return new NanoHTTPD.Response(Response.Status.OK, MIME_JSON, responseString);

Here's the ClockServer class:

import android.content.res.Resources;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;


public class ClockServer extends NanoHTTPD {

    private static final String MIME_JSON = "application/json";
    private Clock clock;

    public ClockServer(Clock clock, int port) {
        super(port);
        this.clock = clock;
    }

    @Override
    public Response serve(IHTTPSession session) {
        try {
            Method method = session.getMethod();
            String uri = session.getUri();
            Map<String, String> parms = session.getParms();
            String responseString = serveClock(session, uri, method, parms);
            return new NanoHTTPD.Response(Response.Status.OK, MIME_JSON, responseString);

        } catch (IOException ioe) {
            return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
        } catch (ResponseException re) {
            return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
        } catch (NotFoundException nfe) {
            return new NanoHTTPD.Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found");
        } catch (Exception ex) {
            return new Response(Response.Status.INTERNAL_ERROR, MIME_HTML, "<html><body><h1>Error</h1>" + ex.toString() + "</body></html>");
        }
    }

    private String serveClock(IHTTPSession session, String uri, Method method, Map<String, String> parms)  throws IOException, ResponseException {
        String responseString = "";
        do {
            if(Method.GET.equals(method)) {
                responseString = handleGet(session, parms);
                break;
            }

            if(Method.POST.equals(method)) {
                responseString = handlePost(session);
                break;
            }

            throw new Resources.NotFoundException();

        } while(false);

        return responseString;
    }

    private String handleGet(IHTTPSession session, Map<String, String> parms) {
        return clock.handleRequest("{'name':'status', 'value':''}");
    }

    private String handlePost(IHTTPSession session) throws IOException, ResponseException {
        Map<String, String> files = new HashMap<String, String>();
        session.parseBody(files);

        return clock.handleRequest(files.get("postData"));
    }


    private class NotFoundException extends RuntimeException {
    }
}