Управление сессиями с помощью Nanohttpd - PullRequest
0 голосов
/ 26 июня 2018

Я пытаюсь создать простое приложение для управления сессиями с помощью 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>

`

sample.html

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