首页 > 解决方案 > 使用 Nanohttpd 进行会话管理

问题描述

我正在尝试使用 Nanohttpd 创建简单的会话管理应用程序。我已使用以下项目供参考。 https://github.com/lopspower/AndroidWebServer

我有两个简单的 html 页面(sample3.html 和 sample.html),我想为输入类型创建会话name。按下提交后,名称值应从会话值打印在sample.html上。如果用户单击Logout按钮,则应销毁会话。我已经从参考中完成了以下代码。任何人都可以帮助我吗?提前致谢。

AndroidWebServer.java

public class AndroidWebServer extends NanoHTTPD {

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

    public AndroidWebServer(String hostname, int port) {
        super(hostname, port);
    }

    @Override
    public Response serve(IHTTPSession session) {
        String html=null;
        try {
            InputStream is = new FileInputStream("/sdcard/sample3.html");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            html = new String(buffer, "UTF-8");

        } catch (IOException ex) {
            ex.printStackTrace();
            //return null;
        }
        Map<String, String> files = new HashMap<String, String>();
        Method method = session.getMethod();
        String postParameter="";

        if (Method.POST.equals(method)) {
            try {
                session.parseBody(files);
            } catch (IOException ioe) {
            } catch (ResponseException re) {
            }
        }

        String postBody = session.getQueryParameterString();
        postParameter = session.getParms().get("name");
        Log.d("Postbody",postBody+"\n"+postParameter);
        if(postParameter!=null){
            Log.d(TAG, "serve: inside post body ");
            session.getCookies().set(new Cookie("name", postParameter));

            try {
                InputStream is = new FileInputStream("/sdcard/sample.html");
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                html = new String(buffer, "UTF-8");

            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return newFixedLengthResponse(html +"  "+ session.getCookies().read("name"));
        }
        return newFixedLengthResponse(html);
    }
}

sample3.html

<html>
<head>
    <h1>Welcome to the Form</h1>
<head/>
<body>
    <form action='' method='post'>
        <p>Enter Name:</p><input type='text' name='name'>
        <br>
        <input type="submit" name="Submit">
    </form>
</body></html>

`

示例.html

<html>
<body>
    <p>Get name from sample.html here</p>
    <input type="button" value="Logout"/>
</body>
</html>

标签: javaandroidsessionnanohttpd

解决方案


推荐阅读