Skip to content Skip to sidebar Skip to footer

Read Ajax Post Content Using Java Socket Server

I set up a JAVA socket server that is able to get everything from a html < form >. But when it comes to AJAX post, the server can only get the POST event, but it cannot read

Solution 1:

POST data in HTTP request come as a request body, which is separated from head by empty line like this:

POST / HTTP/1.1
Host: 10.0.1.1:80Connection: keep-aliveContent-Length: 29Content-Type: text/json{"id":123,"name":"something"}

So your server code should (more or less) ;-) look like this:

BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

String line;
List<String> headers = new LinkedList<>();
StringBuilder body = null;
while ((line = in.readLine()) != null) {
    //- Here we test if we've reach the body part.if (line.isEmpty() && body == null) {
        body = new StringBuilder();
        continue;
    }
    if (body != null) {
        body.append(line).append('\n');
    }
    else {
        headers.add(line);
    }
}

System.out.println("--- Headers ---");
for (String h : headers) {
    System.out.println(h);
}
System.out.println("--- Body ---");
System.out.println(body != null ? body.toString() : "");

Please note, that this code is only for test purposes. You can not assume, that body is a text (at least you should verify Content-Type header) and you can safely read it into StringBuilder or if it is safe at all to load it in whole into memory (at least you should verify Content-Length header). Despite of those headers you should expect the worst and during reading perform some sanity checks.

Post a Comment for "Read Ajax Post Content Using Java Socket Server"