NanoHTTPD unable to process POST parameters

3.5k views Asked by At

I have downloaded newest NanoHTTPD from link: https://raw.githubusercontent.com/NanoHttpd/nanohttpd/master/core/src/main/java/fi/iki/elonen/NanoHTTPD.java

When processing very basic POST example, calling session.getParms() returns empty map. My code is:

@Override
public Response serve(IHTTPSession session) {
    System.out.println( session.getMethod() + " " + session.getParms() );
    return newFixedLengthResponse("Some response.");
}

Which returns:

{}

HTML code triggering nanoHTTPD is:

<html>
<body>
<form action="http://localhost:3388" method="POST">
    <input type="text" name="username" value="a" />
    <input type="submit" />
</form>

</body>
</html>

That all looks good. Do you see anything suspicious in my code, or just nanoHTTPD is not mature enough?

2

There are 2 answers

1
ZulNs On

session.parseBody() only needed if you upload one or more files. Your codes are fine except you must provide enctype="multipart/form-data" in your html form tag. So your html code should be:

<html>
<body>
<form action="http://localhost:3388" enctype="multipart/form-data" method="POST">
    <input type="text" name="username" value="a" />
    <input type="submit" />
</form>

</body>
</html>

0
BottleMan On

You should do parseBody before get parameters when you handle a POST request.

In your code, just like this:

@Override
public Response serve(IHTTPSession session) {
    session.parseBody(new HashMap<String, String>());
    System.out.println( session.getMethod() + " " + session.getParms() );
    return newFixedLengthResponse("Some response.");
}