Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am playing with 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();
    });
  });

}
like image 455
Daniel Robinson Avatar asked Dec 19 '13 11:12

Daniel Robinson


2 Answers

You can use :

import 'dart:convert' show utf8;

Future<String> content = utf8.decodeStream(request);
like image 94
Alexandre Ardhuin Avatar answered Nov 13 '22 02:11

Alexandre Ardhuin


Alexandre Ardhuin gave the short and correct answer, for anyone wanting to see 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();
}
like image 42
Daniel Robinson Avatar answered Nov 13 '22 03:11

Daniel Robinson