如何在实施NanoHTTPD POST
方法时检索HTTP serve
请求正文?
我已尝试使用getInputStream()
IHTTPSession
方法,但在SocketTimeoutException
方法中使用serve
时,我总是得到{{1}}。
答案 0 :(得分:24)
在serve
方法中,您首先必须致电session.parseBody(files)
,其中files
为Map<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");
此值将保留您的帖子正文。
答案 2 :(得分:9)
我认为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
!