Drarig29 Drarig29 - 1 year ago 61
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

and writes to its

private class HttpResponseThread extends Thread {

Socket socket;
String h1;

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

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>" +

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(response + "\r\n");

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


MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
} catch (IOException e) {

For instance, with the url
, the output is :

Request of /?foo=bar from "client_ip"

Here I can easily retrieve the GET data (
). 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 Source

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: