面试题答案
一键面试- 添加依赖:
在
pubspec.yaml
文件中添加dio
依赖:
dependencies:
dio: ^[具体版本号]
然后运行flutter pub get
。
- 构建请求体: 假设请求体需要包含字符串、数字、列表,例如:
Map<String, dynamic> requestBody = {
'stringField': '这是一个字符串',
'numberField': 123,
'listField': ['item1', 'item2']
};
- 设置请求头进行身份验证:
假设使用
Bearer Token
进行身份验证:
Map<String, String> headers = {
'Authorization': 'Bearer [你的令牌]'
};
- 发起POST请求:
import 'package:dio/dio.dart';
void sendPostRequest() async {
Dio dio = Dio();
try {
Response response = await dio.post(
'[你的API地址]',
data: requestBody,
options: Options(
headers: headers
)
);
print(response.data);
} catch (e) {
print('请求出错: $e');
}
}
关键代码总结:
// 构建请求体
Map<String, dynamic> requestBody = {
'stringField': '这是一个字符串',
'numberField': 123,
'listField': ['item1', 'item2']
};
// 设置请求头
Map<String, String> headers = {
'Authorization': 'Bearer [你的令牌]'
};
// 发起POST请求
Response response = await dio.post(
'[你的API地址]',
data: requestBody,
options: Options(
headers: headers
)
);