Drarig29 Drarig29 - 3 months ago 9
HTTP Question

Retrieve POST data with HTTP server hosted on Android

I found an example of how to implement a HTTP server hosted on Android.
It works fine with HTTP GET method.

Here's the code that reads the

Socket
's
InputStream
and writes to its
OutputStream
:

private class HttpResponseThread extends Thread {

Socket socket;
String h1;

HttpResponseThread(Socket socket, String msg) {
this.socket = socket;
h1 = msg;
}

@Override
public void run() {
BufferedReader br;
PrintWriter pw;
String request;

try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
request = br.readLine();

pw = new PrintWriter(socket.getOutputStream(), true);

String response =
"<html><head></head>" +
"<body>" +
"<h1>" + h1 + "</h1>" +
"</body></html>";

pw.print("HTTP/1.0 200" + "\r\n");
pw.print("Content type: text/html" + "\r\n");
pw.print("Content length: " + response.length() + "\r\n");
pw.print("\r\n");
pw.print(response + "\r\n");
pw.flush();

msgLog += String.format("Request of %s from %s\n", request, socket.getInetAddress().toString());

socket.close();

MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
infoMsg.setText(msgLog);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}


For instance, with the url
<android_device_ip>:<server_port>?foo=bar
, the output is :


Request of /?foo=bar from "client_ip"


Here I can easily retrieve the GET data (
foo=bar
). But instead of using HTTP GET method, I'd like to use HTTP POST method...

But I don't see how to do it.

PS : for more information about the rest of the code, see here.

Answer

HTTP POST data is stored in the HTTP payload section of a message. So, in order to retrieve them you would need to first parse the payload part. To do this, simplest way is reading from the input stream until you reach "\r\n\r\n". After facing this pattern, the rest is called payload. So, you will have got two parts:

  • Before "\r\n\r\n": This part is HTTP headers separated by "\r\n".

  • After "\r\n\r\n": This part is HTTP POST data in the form of:

    key1=value1&key2=value2&...
    
Comments