flutter 使用http 发送post 包含application/x-www-form-urlencoded格式1
时间: 2024-10-19 17:03:55 浏览: 33
在Flutter中,如果你需要通过HTTP发送POST请求,包含`application/x-www-form-urlencoded`格式的数据,你可以使用内置的`dio`库。首先,你需要在pubspec.yaml文件中添加`dio`依赖:
```yaml
dependencies:
dio: ^4.0.0
```
然后,在 Dart 代码中,可以按照以下步骤进行操作:
1. 引入`dio`库:
```dart
import 'package:dio/dio.dart';
```
2. 创建DIO实例:
```dart
final dio = Dio();
```
3. 准备数据(这里是一个示例,替换为你实际的数据):
```dart
Map<String, String> formData = {
'key1': 'value1',
'key2': 'value2',
};
```
4. 发起POST请求,设置Content-Type为`application/x-www-form-urlencoded`:
```dart
Future<void> sendPostRequest() async {
try {
// 设置请求体为form-data格式
final options = Options(
contentType: MediaType('application', 'x-www-form-urlencoded'),
);
// 发送POST请求
final response = await dio.post(
'https://your-api-url.com/endpoint', // 替换为你的API地址
data: formData,
options: options,
);
print('Response status: ${response.statusCode}');
print('Response data: ${response.data}');
} on DioError catch (e) {
print('Error: $e');
}
}
```
最后,调用`sendPostRequest()`函数发起请求。
阅读全文
相关推荐














