How to get response body with request.send() in dart
DartFlutterDart Problem Overview
I'm doing an api request uploading an image with
var request = new http.MultipartRequest("POST", uri);
var response = await request.send()
in dart using flutter. I can then check the response code with for instance
if (response.statusCode == 200) {
print('ok');
}
with other calls I can also get the response body with
var result = response.body;
however when using request.send() I can't seem to find out how to get the response body result.
Any help or input is very much appreciated, thanks!
Dart Solutions
Solution 1 - Dart
I checked the docs for request.send I returns Future<StreamedResponse>
instead of Future<Response>
Digging more for StreamedResponse I found that it response.stream
which is a ByteStream
Here is what you can do to get response in String
final response = await request.send();
final respStr = await response.stream.bytesToString();
In my opinoin you should only use request.send if you want streamed response instead of "collected" response. More about streams in dart here
Solution 2 - Dart
Just use http.Response.fromStream()
import 'package:http/http.dart' as http;
var streamedResponse = await request.send()
var response = await http.Response.fromStream(streamedResponse);
Solution 3 - Dart
You can cast after first response, look :
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(()
{});
Solution 4 - Dart
So this is my expected json object:
{"hasErrors":true,"errorMessage":"Some Error Message","done":false}
On the basis of 'hasErrors' property I want to perform some action.
This is how I get it from Http Post Request:
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'];
Solution 5 - Dart
Your MultipartRequest
returns a Streamed Response
since you used request.send
. You will need to extract the string value from the response like below:
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();
In this case the responseString
will be just like response.body
of
final response = await post(URL, body : map);
Solution 6 - Dart
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']);
Solution 7 - Dart
What worked for me was,
await res.stream.transform(utf8.decoder).transform(json.decoder).first;