Retrieve HTTP Body in NanoHTTPD

前端 未结 3 1312
一生所求
一生所求 2021-02-07 03:01

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

I\'ve tried to use the getInputStream() m

3条回答
  •  一个人的身影
    2021-02-07 03:50

    In the serve method you first have to call session.parseBody(files), where files is a Map, 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 files = new HashMap();
        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.
    }
    

提交回复
热议问题