【发布时间】:2021-03-03 16:19:40
【问题描述】:
我想使用 Dio 在我的发布请求的授权标头中设置一个令牌。我尝试使用两个选项设置标题。两者都不起作用。第一种方式抛出错误,第二种方式,没有数据发送到服务器。从共享首选项添加授权令牌并使用 Dio() 在发布请求中将其作为标头发送的最佳方法是什么
当用户登录并访问它时,我将令牌保存在 SharedPreference 上,如下所示
String token = "";
@override
void initState() {
getToken();
}
void getToken() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
token = prefs.getString("token");
setState((){});
}
第一种发送数据的方式
Future<FormsModel> createEntry(
String id,
String formName,
String dataContent,
String dateCreated,
String dateUpdated,
String userLocation,
String imeI,
String updatedBy) async {
String apiUrl = "http://10.0.2.2:8080/api/v1/entry";
Dio().options.headers["Authorization"] = "Bearer $token";
await Dio().post(apiUrl, data: {
"id": id,
"formName": formName,
"dataContent": dataContent,
"dateCreated": dateCreated,
"dateUpdated": dateUpdated,
"userLocation": userLocation,
"imeI": imeI,
"updatedBy": updatedBy
});
引发错误
未处理的异常:DioError [DioErrorType.RESPONSE]:Http 状态 错误 [302]
第二种将令牌添加到标头的方式
Future<FormsModel> createEntry(
String id,
String formName,
String dataContent,
String dateCreated,
String dateUpdated,
String userLocation,
String imeI,
String updatedBy) async {
String apiUrl = "http://10.0.2.2:8080/api/v1/entry";
await Dio().post(apiUrl, data: {
"id": id,
"formName": formName,
"dataContent": dataContent,
"dateCreated": dateCreated,
"dateUpdated": dateUpdated,
"userLocation": userLocation,
"imeI": imeI,
"updatedBy": updatedBy
},
options: Options( headers: {"authorization": "Bearer $token"},
followRedirects: false,
validateStatus: (status) { return status < 500; }));
}
这样我不会出错,但没有数据发送到服务器。
【问题讨论】:
-
查看这个答案以获得最强大的解决方案stackoverflow.com/questions/60745811/…
标签: flutter dart authorization access-token