Flutter Dio Cant发出POST请求

时间:2020-03-10 07:27:29

标签: android http flutter server

正在尝试使用Dio插件在Flutter应用程序中执行POST请求。我有以下代码,我似乎不知道为什么它不起作用。它会将空数据发送到我的API。

代码:

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;

}

但是在POSTMAN中发送请求是可行的。

请帮助。谢谢!。

2 个答案:

答案 0 :(得分:1)

这意味着您正在使用服务器formData,并且正在通过data参数发送数据。据我所知Dio不支持formData。要解决此问题,您应该更改您的API以适合此要求,或者使用http软件包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'));

答案 1 :(得分:1)

尝试一下:

Future<String> sendRequest(String phone, int status) async {
String status = '';
print(sendConnectionUrl);
String bearerToken = await Endpoints.getBearerToken();
Formdata form=FormData.fromMap({
"mobile": phone, "status": status
})

try {
  Response response = await Dio().post(
    'https://my.web.server/api',
    data: form,
    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;