Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve HTTP Body in NanoHTTPD

Tags:

How can I retrieve the HTTP POST request body when implementing NanoHTTPDs serve method?

I've tried to use the getInputStream() method of IHTTPSession already, but I always get an SocketTimeoutException when using it inside of the serve method.

like image 497
miho Avatar asked Mar 12 '14 11:03

miho


2 Answers

In the serve method you first have to call session.parseBody(files), where files is a Map<String, String>, and then session.getQueryParameterString() will return the POST request's body.

I found an example in the source code. Here is the relevant code:

public Response serve(IHTTPSession session) {     Map<String, String> files = new HashMap<String, String>();     Method method = session.getMethod();     if (Method.PUT.equals(method) || Method.POST.equals(method)) {         try {             session.parseBody(files);         } catch (IOException ioe) {             return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());         } catch (ResponseException re) {             return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());         }     }     // get the POST body     String postBody = session.getQueryParameterString();     // or you can access the POST request's parameters     String postParameter = session.getParms().get("parameter");      return new Response(postBody); // Or postParameter. } 
like image 194
bob esponja Avatar answered Nov 10 '22 02:11

bob esponja


On a IHTTPSession instance you can call the .parseBody(Map<String, String>) method which will then fill the map you provided with some values.

Afterwards your map may contain a value under the key postBody.

        final HashMap<String, String> map = new HashMap<String, String>();         session.parseBody(map);         final String json = map.get("postData"); 

This value will then hold your posts body.

Code that does this, can be found here.

like image 34
Rin malavi Avatar answered Nov 10 '22 00:11

Rin malavi