首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >颤振http无法从.NET Api获得更多令牌

颤振http无法从.NET Api获得更多令牌
EN

Stack Overflow用户
提问于 2022-05-21 19:28:16
回答 2查看 172关注 0票数 0

我开始颤振移动开发和有问题的http包http调用。我已经用.NET编写了包含Micorosft标识的工作API。我的目标是创建一个颤振移动应用程序,通过授权从API中获取数据。我在实现用户名-密码授权以从API获得令牌时遇到了问题。同样的API调用也适用于邮递员和我现有的Xamarin Forms应用程序。http调用的相同问题,在它的标题中,我使用从邮递员那里得到的令牌。使用VS代码,所有安装的软件包都可以在相同的颤振应用程序中从openweathermap.org中检索样本数据。我的代码是:

  1. 从API接收更多令牌: 未来授权(字符串用户名,字符串密码)异步{ uri Uri = Uri.parse('https://myapi/token');var请求= http.MultipartRequest('POST',uri);request.fields.addAll({‘授予类型’:‘密码’,‘用户名’:用户名,‘密码’:密码,});http.StreamedResponse响应=等待request.send();if (response.statusCode == 200) { Map auth =jsonDecode(等待response.stream.bytesToString());返回auth‘’access_token‘;}{auth“;} }
  2. 从API获取Cars数据: 未来的getCars()异步{ uri Uri = Uri.parse('https://myapi/api/getcars');var token = 'WorkingToken';http.Response响应=等待http.get(uri,headers:{“Content”:"application/json;charset=UTF-8",“授权”:"Bearer $token",});返回response.body; }
EN

回答 2

Stack Overflow用户

发布于 2022-05-22 16:55:06

Microsoft 授权请求期望application/x-www-form-urlencoded内容。

代码语言:javascript
运行
复制
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);
  }
}
票数 0
EN

Stack Overflow用户

发布于 2022-05-21 23:33:11

你的问题很笼统,你的问题取决于你的反应数据。当然,我没有意识到您在接收令牌或将令牌用作另一个api的头时遇到了问题!但是,由于您刚刚开始使用Flutter,我建议您使用斩波器图书馆来处理HTTP和api。很简单也很有趣。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72332652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档