如何在Dart上从客户端,服务器上读取POST方法发送的HttpRequest数据?
我从客户端发送消息,如下所示:
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);
在服务器上,我正在捕捉这样的请求:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
//DATA SHOULD BE READ HERE
});
});
但我无法弄清楚如何实际读取数据... HttpRequest中没有数据属性也没有其他...
编辑这是我现在得到答案的方式:
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);
});
}
});
});
但由于某种原因,request.method不是“POST”而是“OPTIONS”,如果我改为if(request.method == "OPTIONS")
,那么print(postData)仍然不会返回任何内容......
答案 0 :(得分:1)
目前,处理POST数据有点困难。但基本上HttpRequest本身必须“倾听”。 HttpRequest is a stream itself。特别是它是Stream<List<int>>
。所以基本上你的数据可以作为多个List<int>
传递给你的HttpRequest。所以我们需要重建数据然后将其转换为字符串(假设你期望一个字符串,而不是二进制数据等)。这或多或少都是我做的:
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()(如果数据较大或多部分形式,则可能不会同时出现)。这确保我们缓冲所有内容,直到流表明它已“完成”。在这种情况下,我们现在可以对收到的数据执行某些操作,例如将其转换为字符串。
答案 1 :(得分:1)
您可以使用StringDecoder从HttpRequest中的“List of Int”转换为“String”。因为无论你发送json,纯文本还是png,Dart总是以数据的形式发送数据 服务器的“Int列表”。另一种方法是使用在Heroku Steam上测试的Streams(http://www.dartlang.org/articles/feet-wet-streams/)v0.6.2 Dart编辑器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();
}
}
configure.dart
var _mapping = {
"/": home,
"/png": receivePNG,
};
答案 2 :(得分:1)
我在客户端/侧码
中找到了这个有用的例子GitHub json send to server Example
// 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);
}