java - Recuperar el cuerpo HTTP en NanoHTTPD
(3)
¿Cómo puedo recuperar el cuerpo de la solicitud HTTP POST al implementar el método de serve NanoHTTPD ?
Ya intenté usar el método getInputStream() de IHTTPSession , pero siempre obtengo una SocketTimeoutException cuando lo uso dentro del método serve .
Creo que session.getQueryParameterString(); No funciona en este caso.
Si utiliza POST , PUT , debería intentar este código:
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));
De hecho, probé IOUtils.toString(inputstream, encoding) pero causó una Timeout exception !
En el método de serve , primero debe llamar a session.parseBody(files) , donde los files son un Map<String, String> y luego session.getQueryParameterString() devolverá el cuerpo de la solicitud POST .
Encontré un ejemplo en el código fuente. Aquí está el código relevante:
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.
}
En una instancia de IHTTPSession puede llamar al .parseBody(Map<String, String>) que luego llenará el mapa que proporcionó con algunos valores.
Posteriormente, su mapa puede contener un valor debajo de la clave postBody .
final HashMap<String, String> map = new HashMap<String, String>();
session.parseBody(map);
final String json = map.get("postData");
Este valor entonces mantendrá su cuerpo de mensajes.