[英]Flutter http can't get Bearer Token from .NET Api
我正在開始顫動移動開發,並且遇到了 http 包 http 調用的問題。 我已經有了用 .NET 編寫的工作 API,其中包含 Micorosft Identity。 我的目標是創建 Flutter 移動應用程序,通過授權從該 API 獲取數據。 我在實施用戶名密碼授權以從 API 獲取令牌時遇到問題。 相同的 API 調用適用於 Postman 和我現有的 Xamarin Forms 應用程序。 與 http 調用相同的問題,我在其標頭中使用從 Postman 獲得的令牌。 使用 VS Code,安裝的所有包都可以在同一個 Flutter 應用程序中從 openweathermap.org 檢索示例數據。 我的代碼是:
從 API 接收承載令牌:
Future<String> authorization(String username, String password) async { Uri uri = Uri.parse('https://myapi/token'); var request = http.MultipartRequest('POST', uri); request.fields.addAll({ 'grant_type': 'password', 'username': username, 'password': password, }); http.StreamedResponse response = await request.send(); if (response.statusCode == 200) { Map<String, dynamic> auth = jsonDecode(await response.stream.bytesToString()); return auth['access_token']; } else { return ""; }
}
從 API 獲取汽車數據:
Future<String> getCars() async { Uri uri = Uri.parse('https://myapi/api/getcars'); var token = 'WorkingToken'; http.Response response = await http.get(uri, headers: { "Content-Type": "application/json; charset=UTF-8", "Authorization": "Bearer $token", }); return response.body;
}
Microsoft 身份授權請求需要application/x-www-form-urlencoded
內容。
Future<String> authorization(String username, String password) async {
final response = await http.post(
Uri.parse('https:/host/path/token'),
headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded',
},
body: <String, String>{
'grant_type': 'password',
'username': username,
'password': password,
},
encoding: Encoding.getByName('utf-8')
);
if (response.statusCode == 200) {
return jsonDecode(response.body)['access_token'];
} else {
throw Exception(response.reasonPhrase);
}
}
您的問題非常籠統,您的問題取決於您的響應數據。 當然,我沒有意識到您在接收令牌或將令牌用作另一個 api 的標頭時遇到問題! 但是由於你剛剛開始使用 Flutter,我建議你使用Chopper 庫來處理 HTTP 服務和 api。 這是非常簡單和快速的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.