3

I'm trying to create simple application for session management using Nanohttpd. I have used below project for reference. https://github.com/lopspower/AndroidWebServer

I have two simple html page(sample3.html & sample.html) from them I want to create session for input type name. Once submit is pressed, the name value should be printed on sample.html from session value. If user clicks on Logout button then session should be destroyed. I have done the following code from reference. Can anyone help me in this? Thanks in advance.

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>

0 Answers0