飞镖,您如何阅读http请求的内容正文?

时间:2013-12-19 11:06:58

标签: xmlhttprequest dart

我正在玩dart http服务器,我不知道如何阅读http请求中发送的实际内容:“{'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();
    });
  });

}

2 个答案:

答案 0 :(得分:8)

您可以使用:

import 'dart:convert' show UTF8;

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

答案 1 :(得分:6)

对于想要查看完整代码的人,Alexandre Ardhuin给出了简短而正确的答案:

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();
}