nodejs doesn't consistently fire 'data' event on successful POST from Java program

I wrote some code to periodically post data to a NodeJs program that listens for the POST and prints the data. However, sometimes on the header makes it through and sometimes both the header and the body make it through. Here's the Java code that's posting the data:

JSONObject dataObject = new JSONObject();
dataObject.put("test", "true");
URLConnection urlConn = thisSubUrl.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput(true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream());
String dataStr = dataObject.toString();
wr.write(dataStr, 0, dataStr.length());
wr.flush();
wr.close();

BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
in.close();

The server code looks like this:

var server= http.createServer(function(req,res){
req.setEncoding('utf8');
console.log(req.headers);
req.on('data', function(chunk) {
          console.log("Receive_Event::" + chunk);
         });
req.on('end', function() {
    console.log('on end');
});

console.log("Bytes received: " + req.socket.bytesRead);
if(req.method=='POST'){
    handlePost(req,res);
} else{
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end();
}
}).listen(1338, "127.0.0.1");

The header is always printed out. The number of bytes received varies in length, between the number of the bytes in the header and the number of bytes in the header + the body length.

Why does this happen?

What is probably happening is that you will emit the res.end() (don't know what handlePost actually does) before you have received all the "data" chunks. You should call all the extra logic in the "end" event

var server= http.createServer(function(req,res){
    req.setEncoding('utf8');

    console.log(req.headers);

    req.on('data', function(chunk) {
        console.log("Receive_Event::" + chunk);
    });

    req.on('end', function() {
        console.log('on end');
        console.log("Bytes received: " + req.socket.bytesRead);
        if(req.method=='POST'){
            handlePost(req,res);
        } else{
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end();
        }
    });


}).listen(1338, "127.0.0.1");