我从服务器下载了一个ByteStream,即关于用户的数据。在MySql服务器中作为
"username":"Neor","totalCoins":"350"提供这些数据的.php文件的截断部分如下所示:
$data = $stmt->fetchColumn();
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("Cache-Control: public");
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-Length:".strlen($data));
echo $data;我使用这个颤振代码下载数据:
Future<void> downloadData() async {
var url = Uri.parse("https://example.com/mycloud.php");
var request = http.MultipartRequest('POST', url)
..fields["user"] = "Dia";
var response = await request.send();
var stream = response.stream; }在检查下载的ByteStream是否包含任何内容时,我使用了print(stream.length),它输出为137。如何从ByteStream获得我想要的信息?
(如果我的问题有任何不足之处,请告诉我。)
发布于 2022-01-07 00:10:25
对于简单的POST,不应该使用多部分请求。相反,使用更简单的http.post方法。
Future<void> downloadData() async {
final response = await http.post(
Uri.parse('https://example.com/mycloud.php'),
body: <String, String>{
'user': 'Dia',
},
);
final decodedJson = json.decode(response.body);
// if you want to ensure the character set used, replace this with:
// json.decode(utf8.decode(response.bodyBytes));
}如果您确实坚持流的方式,那么您有一个Stream<List<int>>,您希望最初将它转换为一个List<int>。为此使用流上的toList()方法。那你就得把它解码成字符。JSON总是用utf8编码的,所以您可以:
json.decode(utf8.decode(await stream.toList()));(在幕后,http基本上是为您做的;一起收集流并进行字符解码,并将其表示为body。)
发布于 2022-01-06 23:34:52
首先导入‘dart:转换’显示utf8;字符串foo =utf8.decode(字节);然后是Map valueMap = json.decode(foo );
https://stackoverflow.com/questions/70614083
复制相似问题