实现NanoHTTPD的方法时如何检索 HTTPPOST
请求正文?serve
我已经尝试使用的getInputStream()
方法,但是在方法内部使用它时IHTTPSession
总是得到一个。SocketTimeoutException
serve
实现NanoHTTPD的方法时如何检索 HTTPPOST
请求正文?serve
我已经尝试使用的getInputStream()
方法,但是在方法内部使用它时IHTTPSession
总是得到一个。SocketTimeoutException
serve
在serve
方法中,您首先必须调用session.parseBody(files)
,其中files
a Map<String, String>
,然后session.getQueryParameterString()
将返回POST
请求的正文。
我在源代码中找到了一个示例。以下是相关代码:
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.
}
在一个IHTTPSession
实例上,您可以调用该.parseBody(Map<String, String>)
方法,然后该方法将为您提供的地图填充一些值。
之后,您的地图可能会在 key 下包含一个值postBody
。
final HashMap<String, String> map = new HashMap<String, String>();
session.parseBody(map);
final String json = map.get("postData");
然后,此值将保存您的帖子正文。
我认为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
!
这就是我使用 NanoHttp 获取帖子响应正文的方式,它对我有用。非常重要的是要注意,如果您正在处理自己的错误响应代码并希望发送正文,请使用错误输入流而不是 conn.getInputStream() 如果之前关闭连接,这将避免找不到文件异常或损坏管道异常服务器发送了正文。
public HashMap<String, Object> getResponse(HttpURLConnection conn) throws IOException {
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
StringBuilder response = new StringBuilder();
String line;
BufferedReader br;
if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK)
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
else
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
while ((line = br.readLine()) != null)
response.append(line);
conn.disconnect();
return new Gson().fromJson(response.toString(), HashMap.class);