6

How do i read HttpRequest data sent by POST method from client, on the server, in Dart?

I send a message from the client like this:

HttpRequest request = new HttpRequest();
var url = "http://127.0.0.1:8081";
request.open("POST", url, async: false);

String data = 'hello from client'; 
request.send(data);

On server i am catching the request like this:

HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {

//DATA SHOULD BE READ HERE 



});
});

But i cant figure out how to actually read the data... There is not data property in HttpRequest nor anything else...

EDIT This is how i get the answer now:

HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
  //DATA SHOULD BE READ HERE 
  print("got it");
  print(request.method);
  if(request.method == "POST") {
    print("got it 2");
    List<int> dataBody = new List<int>();
    request.listen(dataBody.addAll, onDone: () {
      var postData = new String.fromCharCodes(dataBody);
      print(postData);
      });
    }
 });
});

But for some reason the request.method is not "POST" but "OPTIONS", and if i change to if(request.method == "OPTIONS") , then print(postData) will still return nothing...

4

3 回答 3

1

现在,POST 数据的处理有点困难。但本质上 HttpRequest 本身必须被“倾听”。HttpRequest 本身就是一个流。特别是它是一个Stream<List<int>>. 所以基本上你的数据可以作为多个传递给你的 HttpRequest List<int>。所以我们需要重建数据,然后将其转换为字符串(假设您期望的是字符串,而不是二进制数据等)。这或多或少是我所做的:

HttpServer.bind('127.0.0.1', 8081).then((server) {
  server.listen((HttpRequest request) {
  if(request.method == "POST") {
    List<int> dataBody = new List<int>();
    request.listen(dataBody.addAll, onDone: () {
      var postData = new String.fromCharCodes(dataBody);
      // Do something with the data now.
    });
  }
  request.response.close();
});

请注意,每次数据发送到服务器时,request.listen(dataBody.AddAll, ...)基本上都会调用List.addAll()(在较大数据或多部分表单的情况下,它可能不会一次全部发送)。这可以确保我们将其全部缓冲,直到流指示它“完成”在这种情况下,我们现在可以对收到的数据做一些事情,比如将其转换为字符串。

于 2013-04-08T17:21:45.490 回答
1

您可以使用 StringDecoder 将 HttpRequest 中的“List of Int”转换为“String”。由于无论你发送 json、纯文本还是 png,Dart 总是以“Int 列表”的形式向服务器发送数据。另一种方法是使用 Streams ( http://www.dartlang.org/articles/ feet-wet-streams/ ) 在 Heroku Steam v0.6.2 Dart Editor 0.4.3_r20602 Dat SDK 0.4.3.5_r26062 上测试

例如,

客户端:

 import 'dart:html';
 import 'dart:json' as Json;
 import 'dart:async';
 import 'dart:uri';
 final String data = 'Hello World!';
 void _sendPNG(String pngData) {
 HttpRequest request = new HttpRequest(); // create a new XHR
 // add an event handler that is called when the request finishes
 request.onReadyStateChange.listen((_) 
 {
 if (request.readyState == HttpRequest.DONE &&
 (request.status == 200 || request.status == 0)) {
 // data saved OK.
 print(request.responseText); // output the response from the server
 }
                  }
 );
 // POST the data to the server Async
 print('Sending Photos to the server...');
 var url = "/png";
 request.open("POST", url);
 request.setRequestHeader("Content-Type", "text/plain");
 request.send(data);
 }

服务器:

 import 'dart:io';
 import 'dart:async';
 import 'dart:json' as Json;
 import "package:stream/stream.dart";
 import 'package:xml/xml.dart' as xml;
 import 'package:unittest/unittest.dart';
 import 'package:rikulo_commons/mirrors.dart';
 void receivePNG(HttpConnect connect){
 var request = connect.request;
 var response = connect.response;
 if(request.uri.path == '/png' && request.method == 'POST')
  {
   String png='';
   response.write('The server received png request!');
   //read incoming List<int> data from request and use StringDecoder to transform   incoming data to string
   var stream = request.transform(new StringDecoder());
   stream.listen((value){
   print(value);
   //Hello World!
  }
  else
  {
   response.write('error');
   response.statusCode = HttpStatus.NOT_FOUND;
   connect.close();
   }
  }

配置.dart

 var _mapping = {
  "/": home,
  "/png": receivePNG,
 };
于 2013-04-08T18:53:18.740 回答
1

我在客户端/端代码中找到了这个有用的示例

GitHub json 发送到服务器示例

// XXX: Dart Editor thinks this is OK, but I haven't run it.

import 'dart:html';

String encodeMap(Map data) {
  return data.keys.map((k) {
    return '${Uri.encodeComponent(k)}=${Uri.encodeComponent(data[k])}';
  }).join('&');
}

loadEnd(HttpRequest request) {
  if (request.status != 200) {
    print('Uh oh, there was an error of ${request.status}');
    return;
  } else {
    print('Data has been posted');
  }
}

main() {
  var dataUrl = '/registrations/create';
  var data = {'dart': 'fun', 'editor': 'productive'};
  var encodedData = encodeMap(data);

  var httpRequest = new HttpRequest();
  httpRequest.open('POST', dataUrl);
  httpRequest.setRequestHeader('Content-type', 
                               'application/x-www-form-urlencoded');
  httpRequest.onLoadEnd.listen((e) => loadEnd(httpRequest));
  httpRequest.send(encodedData);
}
于 2014-07-14T14:53:38.087 回答