HttpRequest JSON string truncated

1,475 views
Skip to first unread message

Hesh

unread,
Oct 5, 2013, 1:21:49 AM10/5/13
to mi...@dartlang.org
I am creating objects on client side and trying to save them on the server side. 
However, I find that the JSON string sent from the client side is truncated when received on the server side, and is never more than 582 characters in length.

I am wondering why, and what can be done to send data longer than 582 characters?

My code below is adapted from Chris Buckett's tutorial (https://www.dartlang.org/articles/json-web-service/)

On the client end:
save() {
  HttpRequest request = new HttpRequest(); 
  request.withCredentials = true;
  request.onReadyStateChange.listen((_) {
    if (request.readyState == HttpRequest.DONE && (request.status == 200 || request.status == 0)) {
      print(request.responseText);
    }
  });

  var objAsMap = toMap(myObject); //creates a map from dart object
  var objAsJson = JSON.stringify(objAsMap);
  request.open("POST", url, async: true);
  request.send(objAsJson);
}

On server side:
void handlePost(HttpRequest req) {
  HttpResponse res = req.response;
  req.listen((List dat) {
  String buffer = UTF8.decode(dat);
    print ("buffer length: ${buffer.length}"); // <== Never more than 582
save(buffer).then((_) => res.close());
  },
  onError: printError);
}

Thanks,

Hesh

Anders Johnsen

unread,
Oct 5, 2013, 4:57:36 AM10/5/13
to General Dart Discussion
Hi Hesh,

The problem you are having, is that you don't wait for all data to arrive on the server. When you listen on a HttpRequest, the data will arrive in chunks, and it's not until 'onDone' on the stream is called, that all data is received. The following should do it for you:

void handlePost(HttpRequest req) {
  HttpResponse res = req.response;
  var buffer = new StringBuffer();
  req.transform(UTF8.decoder)
    .listen((String data) => buffer.write(data),
            onDone: () {
              print ("buffer length: ${buffer.length}"); // <== Print full length
save(buffer.toString()).then((_) => res.close());
            },
            onError: printError);
}

Cheers,

- Anders


--
For other discussions, see https://groups.google.com/a/dartlang.org/
 
For HOWTO questions, visit http://stackoverflow.com/tags/dart
 
To file a bug report or feature request, go to http://www.dartbug.com/new

To unsubscribe from this group and stop receiving emails from it, send an email to misc+uns...@dartlang.org.

Hesh

unread,
Oct 5, 2013, 7:48:14 AM10/5/13
to mi...@dartlang.org
Perfect! Worked like a charm.
Thanks, Anders.

- Hesh
Reply all
Reply to author
Forward
0 new messages