如何在Dart中使用request.send()获取响应主体

Mat*_*ias 6 dart flutter

我正在做一个api请求,上传带有

var request = new http.MultipartRequest("POST", uri);
var response = await request.send()
Run Code Online (Sandbox Code Playgroud)

用飞镖飞镖。然后,我可以检查响应代码,例如

if (response.statusCode == 200) {
   print('ok');
}
Run Code Online (Sandbox Code Playgroud)

与其他电话,我也可以得到响应主体

var result = response.body;
Run Code Online (Sandbox Code Playgroud)

但是,当使用request.send()时,我似乎找不到如何获取响应正文结果的方法。

非常感谢任何帮助或投入,谢谢!

Dev*_*wal 57

只需使用 http.Response.fromStream()

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

var streamedResponse = await request.send()
var response = await http.Response.fromStream(streamedResponse);
Run Code Online (Sandbox Code Playgroud)

  • 嗨,使用这种方法 print(resBody); 银行名称 = resBody['数据']['银行名称']; 但出现错误 Unhandled Exception: NoSuchMethodError: The method '[]' was called on null。E/flutter (13761): 接收者: null E/flutter (13761): 尝试调用: []("BankName") (2认同)

小智 10

这是我期望的 json 对象:

 {"hasErrors":true,"errorMessage":"Some Error Message","done":false}
Run Code Online (Sandbox Code Playgroud)

根据“hasErrors”属性,我想执行一些操作。

这是我从 Http Post 请求中获取它的方式:

  var request = http.Request('POST', url);
  request.body = json.encode(data);
  request.headers.addAll(headers);

  var streamedResponse = await request.send();
  var response = await http.Response.fromStream(streamedResponse);
  final result = jsonDecode(response.body) as Map<String, dynamic>;
  return !result['hasErrors'];
Run Code Online (Sandbox Code Playgroud)


Har*_*dia 8

我检查了文档的request.send我返回Future<StreamedResponse>而不是Future<Response>

StreamedResponse挖掘更多信息,我发现它response.streamByteStream

这是您可以获取String响应的方法

final response = await request.send();
final respStr = await response.stream.bytesToString();
Run Code Online (Sandbox Code Playgroud)

在我的视觉观点中,如果要流式响应而不是“已收集”响应,则仅应使用request.send。有关此处的Dart流的更多信息

  • 所以如果我不想要流式响应,但我想发送多部分请求,我应该怎么做? (2认同)

Álv*_*ero 7

您可以在第一次回复后进行投射,看:

var postUri = Uri.parse("http://my-api.com/updatePhoto");
var request = new http.MultipartRequest("POST", postUri);

request.fields['user_id'] = user_id

request.files.add(await http.MultipartFile.fromPath(
  'photo',
  myPhoto.absolute.path,
  contentType: new MediaType('application', 'x-tar'),
));

request.send().then((result) async {

  http.Response.fromStream(result)
      .then((response) {

    if (response.statusCode == 200)
    {
      print("Uploaded! ");
      print('response.body '+response.body);
    }

    return response.body;

  });
}).catchError((err) => print('error : '+err.toString()))
    .whenComplete(()
{});
Run Code Online (Sandbox Code Playgroud)


小智 5

在下面的示例中,这对我有用,我解码响应到我的模型类(UserModel)的流

 var streamedResponse = await request.send();
        var response = await http.Response.fromStream(streamedResponse);
        if (response.statusCode == 200) {
          var parsed = jsonDecode(response.body);
          UserModel userModel= UserModel.fromJson(parsed);
          return userModel;
}
else{
print(error);
}
Run Code Online (Sandbox Code Playgroud)