轻量级的java HTTP Server——NanoHttpd

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qincidong/article/details/82656569

NanoHTTPD是一个免费、轻量级的(只有一个Java文件) HTTP服务器,可以很好地嵌入到Java程序中。支持 GET, POST, PUT, HEAD 和 DELETE 请求,支持文件上传,占用内存很小。
github地址:https://github.com/NanoHttpd/nanohttpd

maven依赖:

<dependency>
    <groupId>org.nanohttpd</groupId> <!-- <groupId>com.nanohttpd</groupId> for 2.1.0 and earlier -->
    <artifactId>nanohttpd</artifactId>
    <version>2.2.0</version>
</dependency>


官网demo:

 package com.example;

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

import fi.iki.elonen.NanoHTTPD;
// NOTE: If you're using NanoHTTPD >= 3.0.0 the namespace is different,
//       instead of the above import use the following:
// import org.nanohttpd.NanoHTTPD;

public class App extends NanoHTTPD {

    public App() throws IOException {
        super(8080);
        start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        System.out.println("\nRunning! Point your browsers to http://localhost:8080/ \n");
    }

    public static void main(String[] args) {
        try {
            new App();
        } catch (IOException ioe) {
            System.err.println("Couldn't start server:\n" + ioe);
        }
    }

    @Override
    public Response serve(IHTTPSession session) {
        String msg = "<html><body><h1>Hello server</h1>\n";
        Map<String, String> parms = session.getParms();
        if (parms.get("username") == null) {
            msg += "<form action='?' method='get'>\n  <p>Your name: <input type='text' name='username'></p>\n" + "</form>\n";
        } else {
            msg += "<p>Hello, " + parms.get("username") + "!</p>";
        }
        return newFixedLengthResponse(msg + "</body></html>\n");
    }
}

运行App,浏览器打开http://localhost:8080/ 即可看到效果。

输入username,然后回车:

这样一个简单的登录功能就完成了。

问题:
如果form中指定action为post,你会发现后台session获取不到参数。
解决办法:

session.parseBody(new HashMap());
params = session.getParms();

意思也就是,对于post请求,你需要先调用parseBody()方法,直接传一个简单的新构造的map就行了,然后再调用getParams()方法。
参考:https://blog.csdn.net/obguy/article/details/53841559

示例代码:https://gitee.com/qincd/my-test-projects/tree/master/test1下的com.tommy.core.test.nanohttpd包下。

猜你喜欢

转载自blog.csdn.net/qincidong/article/details/82656569