flutter 如何在dart中使用request.send()获取响应正文

ddarikpa  于 2023-01-27  发布在  Flutter
关注(0)|答案(8)|浏览(227)

我正在做一个API请求上传一个图像

var request = new http.MultipartRequest("POST", uri);
var response = await request.send()

在dart中使用flutter。然后我可以检查响应代码,例如

if (response.statusCode == 200) {
   print('ok');
}

我也可以通过以下方式获得响应主体

var result = response.body;

然而,当使用request.send()时,我似乎找不到如何获得响应主体结果。
任何帮助或输入是非常感谢,谢谢!

mbzjlibv

mbzjlibv1#

我检查了request.send的文档,返回了Future<StreamedResponse>而不是Future<Response>
深入挖掘StreamedResponse,我发现它是response.stream,也就是ByteStream
下面是可以用String格式获得响应的方法

final response = await request.send();
final respStr = await response.stream.bytesToString();

在我看来,如果你想要流式响应而不是“收集”响应,你应该只使用request.send。

izj3ouym

izj3ouym2#

只需使用http.Response.fromStream()

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

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

yizd12fk3#

你可以在第一次回应后投,看:

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(()
{});
bvn4nwqk

bvn4nwqk4#

这就是我期望的json对象:

{"hasErrors":true,"errorMessage":"Some Error Message","done":false}

基于“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'];
nzk0hqpo

nzk0hqpo5#

由于使用了request.sendMultipartRequest返回了Streamed Response。您需要从响应中提取字符串值,如下所示:

import 'package:http/http.dart'

var request = new MultipartRequest("POST", uri);
var response = await request.send()

// Extract String from Streamed Response
var responseString = await response.stream.bytesToString();

在这种情况下,responseString将类似于

final response = await post(URL, body : map);
dnph8jn4

dnph8jn46#

import 'package:http/http.dart'
    import 'dart:convert';
    
    var request = new MultipartRequest("POST", uri);
    var response = await request.send()
    
    // Extract String from Streamed Response
    var responseString = await response.stream.bytesToString();
    final decodedMap = json.decode(responseString);
    print(decodedMap['id']);
    print(decodedMap['name']);
wmvff8tz

wmvff8tz7#

对我有效的是,

await res.stream.transform(utf8.decoder).transform(json.decoder).first;
rggaifut

rggaifut8#

在下面的例子中,我对响应于我的模型类(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);
}

相关问题