在NanoHTTPD中检索HTTP正文
在实现NanoHTTPD的serve
方法时,如何检索HTTP POST
请求体?
我已经尝试使用IHTTPSession
的getInputStream()
方法,但是当在serve
方法中使用它时,我总是得到一个SocketTimeoutException
。
在serve
方法中,首先必须调用session.parseBody(files)
,其中files
是Map
,然后session.getQueryParameterString()
将返回POST
请求的主体。
我在源代码中找到了一个例子 。 这是相关的代码:
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. }
在IHTTPSession
实例上,您可以调用.parseBody(Map
方法,该方法将为您提供的某些值填充地图。
之后,您的地图可能包含密钥postBody
下的值。
final HashMap map = new HashMap(); session.parseBody(map); final String json = map.get("postData");
然后,此值将保留您的post正文。
可以在此处找到执行此操作的代码。
我认为session.getQueryParameterString();
在这种情况下不起作用。
如果您使用POST
, PUT
,您应该尝试以下代码:
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
!