I'm trying to perform a POST request in a Flutter application using the Dio Plugin. I have the following code and I don't seem to know why it's not working. It sends empty data to my API.
Code:
Future<String> sendRequest(String phone, int status) async {
String status = '';
print(sendConnectionUrl);
String bearerToken = await Endpoints.getBearerToken();
try {
Response response = await Dio().post(
'https://my.web.server/api',
data: json.encode({ "mobile": phone, "status": status }),
options: Options(
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + bearerToken
}
)
);
// The code doesnt even get here, it goes straight to the catch
print(response.toString());
print('status: ' + response.statusCode.toString());
var jsonData = json.decode(response.toString());
if (jsonData['error'] == '0') {
status = 'ok';
}
else {
status = 'failed';
}
}
catch (e) {
print('exception: ' + e.toString());
Future.error(e.toString());
}
return status;
}
But sending the request in POSTMAN works.
This means you're server is expecting formData
and you're sending data via data
params. As far as i know Dio
doesn't support formData
. To solve this, you should either change your API to suit this requirement or use http
package here
import 'package:http/http.dart' as http;
var url = 'https://example.com/whatsit/create';
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
print(await http.read('https://example.com/foobar.txt'));