在NanoHTTPD中检索HTTP正文

时间:2014-03-12 11:15:04

标签: java nanohttpd

如何在实施NanoHTTPD POST方法时检索HTTP serve请求正文?

我已尝试使用getInputStream() IHTTPSession方法,但在SocketTimeoutException方法中使用serve时,我总是得到{{1}}。

3 个答案:

答案 0 :(得分:24)

serve方法中,您首先必须致电session.parseBody(files),其中filesMap<String, String>,然后session.getQueryParameterString()将返回POST请求的身体。

我在源代码中找到了an example。以下是相关代码:

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.
}

答案 1 :(得分:18)

IHTTPSession个实例上,您可以调用.parseBody(Map<String, String>)方法,然后使用某些值填充您提供的地图。

之后,您的地图可能会在键postBody下包含一个值。

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

此值将保留您的帖子正文。

Code that does this, can be found here.

答案 2 :(得分:9)

我认为session.getQueryParameterString();在这种情况下不起作用。

如果您使用POSTPUT,则应尝试使用以下代码:

Integer contentLength = Integer.parseInt(session.getHeaders().get("content-length"));
byte[] buffer = new byte[contentLength];
session.getInputStream().read(buffer, 0, contentLength);
Log.d("RequestBody: " + new String(buffer));

事实上,我尝试了IOUtils.toString(inputstream, encoding),但却导致Timeout exception