How to Implement a Simple Http Server in Android

  • 2021-09-11 21:15:37
  • OfStack

Recently, I encountered a requirement to create an Http server in App for browsers to call, using the open source micro Htpp server framework: NanoHttpd, project address: https://github.com/NanoHttpd/nanohttpd

Direct code


public class HttpServer extends NanoHTTPD {

  public HttpServer(int port) {
    super(port);
  }

  @Override
  public Response serve(IHTTPSession session) {

    HashMap<String, String> files = new HashMap<>();
    Method method = session.getMethod();

    if (Method.POST.equals(method)) {
      try {
        //notice:If the post with body data, it needs parses the body,or it can't get the body data;
        session.parseBody(files);
      }catch (IOException e) {
        return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT,
            "SERVER INTERNAL ERROR: IOException: " + e.getMessage());
      }catch (ResponseException e) {
        return newFixedLengthResponse(e.getStatus(), MIME_PLAINTEXT, e.getMessage());
      }
    }

    final String postData = files.get("postData");

    String transJson = Transmit.getInstance().getAuthoriseData(postData);

    return newFixedLengthResponse(transJson);
  }

It can be said to be very simple to use. The session parameter contains all kinds of information of the request. Here, it shows that the request method is obtained. Because we only use post (demo) for the time being in our project, we only deal with post requests, and the processing of get will be simpler. Because the post request has body, it is necessary to declare an HashMap first and take out the key-value pair in body. Here we map the requested json data to "postData", and then start from through "


final String postData = files.get("postData");

This line of code takes it out. session also has getParams (), getCookies (), getHeaders () and other methods. You can know the functions by looking at the names. At this point, a simple Http server comes out, which is usually placed in an service to wait for requests.


Related articles: