Question

I'm writing an HTTP server (for learning purposes). Once I receive an HTTP POST request, I want to print the parameters that were sent by the client, the problem is that I'm sending "name=Marcelo" and I'm getting an incomplete result.

Content length: 12
char 0: 
char 1: 

char 2: n
char 3: a
char 4: m
char 5: e
char 6: =
char 7: M
char 8: a
char 9: r
char 10: c
char 11: e

Here's the code (JS with Java, i.e., Nashorn):

//Initialize an array of characters                        
var content = new CharArray(contentLength);
print('Content length: ' + content.length);

bufReader.read(content);

for(var c in content) {
    print('char ' + c + ': ' + content[c]);
}

I understand that Content-Length is the number of bytes of the request content data (not the number of characters) so, what would be the most efficient way to construct this char array based on the request's Content-Length?

Was it helpful?

Solution

Apparently you're not completely reading the HTTP Headers before reading the POST body. Thus, the first two characters of your content array are \r and \n respectively and the two last characters of the body do not get read.

Fix this by reading 2 newlines after the last HTTP header line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top