【问题标题】:How to get response from streamed response in flutter? [duplicate]如何从颤动的流式响应中获得响应? [复制]
【发布时间】:2020-07-07 13:37:35
【问题描述】:

我正在使用flutter开发一个应用程序,我正在使用http库来调用我构建的api。

我想发出一个多部分请求来发送文件,它也发送它,但我无法从服务器收到任何响应,因为返回的对象是 StreamResponse。

请告诉我如何获取响应的正文。

代码片段:

var request = http.MultipartRequest('POST', Uri.parse('$SERVER_URL/signup'));
    request.files.add(await http.MultipartFile.fromPath(
      'image',
      user.image,
      filename: 'image',
      contentType: MediaType('multipart/form-data', 'multipart/form-data'),
    ));



    StreamResponse x = await request.send();
    //get body of the response


谢谢,

【问题讨论】:

标签: api http flutter dart


【解决方案1】:

只需使用 http.Response.fromStream()

import 'package:http/http.dart' as http;

var streamedResponse = await request.send()
var response = await http.Response.fromStream(streamedResponse);

【讨论】:

    【解决方案2】:

    StreamedResponse 有一个 stream getter,正如您所期望的那样,它提供字节数组流。

    假设您想要字符而不是字节,将它们推送到适当的字符解码器 - 让我们假设 UTF-8。

    然后您可能希望将所有这些连接到一个字符串中,因此我们可以使用join。给你:

      print(await x.stream.transform(utf8.decoder).join());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-18
      • 2021-11-13
      • 2018-09-06
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多