nanohttpd在Java Web开发中的应用

发布时间:2023-05-18

一、什么是nanohttpd

nanohttpd是一个轻量级的Java HTTP服务器,它可以在Java应用程序中嵌入并提供Web服务。 nanohttpd的主要特点包括:

  1. 非常小巧,代码量不到2000行。
  2. 支持HTTPS。
  3. 支持WebSocket。
  4. 可以方便地扩展。
  5. 易于嵌入到任何应用中。

二、如何使用nanohttpd

我们来看一个简单的例子,实现在浏览器上输出"Hello World":

import java.io.IOException;
import fi.iki.elonen.NanoHTTPD;
public class SimpleServer extends NanoHTTPD {
    public SimpleServer(int port) {
        super(port);
    }
    @Override
    public Response serve(IHTTPSession session) {
        String response = "Hello World!";
        return newFixedLengthResponse(response);
    }
    public static void main(String[] args) {
        SimpleServer server = new SimpleServer(8080);
        try {
            server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行程序,打开浏览器,访问 http://localhost:8080/,就能看到"Hello World"了。

三、使用nanohttpd处理GET和POST请求

为了处理GET和POST请求,我们需要根据 IHTTPSession 中的参数来判断请求的类型。 下面是一个处理GET和POST请求的例子:

import java.io.IOException;
import java.util.Map;
import fi.iki.elonen.NanoHTTPD;
public class GetPostServer extends NanoHTTPD {
    public GetPostServer(int port) {
        super(port);
    }
    @Override
    public Response serve(IHTTPSession session) {
        String response = "";
        Method method = session.getMethod();
        switch (method) {
            case GET:
                Map<String, String> getParms = session.getParms();
                if (getParms.containsKey("name")) {
                    String name = getParms.get("name");
                    response += "<h1>Hello " + name + "!</h1>";
                } else {
                    response += "<form method=\"get\" action=\"http://localhost:8080/\">\n" +
                                "  <label for=\"name\">Enter your name:</label>\n" +
                                "  <input type=\"text\" id=\"name\" name=\"name\">\n" +
                                "  <input type=\"submit\" value=\"Submit\">\n" +
                                "</form>";
                }
                break;
            case POST:
                Map<String, String> postParms = new HashMap<String, String>();
                try {
                    session.parseBody(postParms);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ResponseException e) {
                    e.printStackTrace();
                }
                if (postParms.containsKey("name")) {
                    String name = postParms.get("name");
                    response += "<h1>Hello " + name + "!</h1>";
                } else {
                    response += "<form method=\"post\" action=\"http://localhost:8080/\">\n" +
                                "  <label for=\"name\">Enter your name:</label>\n" +
                                "  <input type=\"text\" id=\"name\" name=\"name\">\n" +
                                "  <input type=\"submit\" value=\"Submit\">\n" +
                                "</form>";
                }
                break;
            default:
                response += "<p>Unsupported method: " + method + "</p>";
                break;
        }
        return newFixedLengthResponse(response);
    }
}