Dart, how do you read the body of the http request content?

I play with a dart http server and I'm not sure how to read the actual content sent in the HTTP request: "{'text': 'some text data.'}"

import 'dart:io';


void main() {

  HttpServer.bind('127.0.0.1', 3000).then((server){
    server.listen((HttpRequest request) {
      print("request made");
      request.response.write('''
        <html>
          <head>
          </head>
          <body>
            <pre>
              HELLO:
              request info:
                method: ${request.method}
                uri: ${request.uri}
                content length: ${request.contentLength}
                content : //HOW DO I GET THIS?
            </pre>
            <script>

              var req = new XMLHttpRequest();
              req.open("POST","/a_demonstration");
              req.send("{'text':'some text data.'}");

            </script>
          </body>
        </html>
      ''');
      request.response.close();
    });
  });

}
+4
source share
2 answers

You can use:

import 'dart:convert' show UTF8;

Future<String> content = UTF8.decodeStream(request);
+8
source

Alexandre Ardhuin gave a short and correct answer, for those who want to see the full code:

import 'dart:io';
import 'dart:convert' show UTF8;

void main() {

  HttpServer.bind('127.0.0.1', 3000).then((server){
    server.listen((HttpRequest request) {
      print("request made");
      if(request.contentLength == -1){
        _sendResponse(request, '');
      }else{
        UTF8.decodeStream(request).then((data)=>_sendResponse(request,data));
      }
    });
  });

}

_sendResponse(HttpRequest request, String requestData){
  request.response.write('''
      <html>
      <head>
      </head>
      <body>
      <pre>
      HELLO:
      request info:
      method: ${request.method}
      uri: ${request.uri}
      content length: ${request.contentLength}
      content: ${requestData}
      </pre>
      <script>

      var req = new XMLHttpRequest();
      req.open("POST","/a_demonstration");
      req.send("{'text':'some text data.'}");

      </script>
      </body>
      </html>
  ''');
  request.response.close();
}
+5
source

All Articles