Flutter Dio 无法发出 POST 请求 [关闭]
Posted
技术标签:
【中文标题】Flutter Dio 无法发出 POST 请求 [关闭]【英文标题】:Flutter Dio Can't Make POST Requests [closed] 【发布时间】:2020-06-22 02:01:09 【问题描述】:我正在尝试使用 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 中发送请求是可行的。
【问题讨论】:
【参考方案1】:这意味着您的服务器期待 formData
并且您正在通过 data
参数发送数据。据我所知 Dio
不支持 formData
。要解决这个问题,您应该更改您的 API 以适应此要求或使用 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'));
【讨论】:
【参考方案2】:试试这个:
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;
【讨论】:
【参考方案3】:试试这个
FormData form = FormData.fromMap("url": url);
Response response = await (Dio()).post(requestUrl, data: form, cancelToken: token);
【讨论】:
以上是关于Flutter Dio 无法发出 POST 请求 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
包含在 Flutter 中使用 Dio 的 POST API 的项目列表的参数