You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何从API响应体获取access_token?

正确提取Microsoft OAuth2响应中的access_token

你的问题出在两个核心点:

  • access_token是响应体的JSON数据字段,不在响应头里,所以response.headers["access_token"]必然返回null;
  • response.body本质是字符串类型,不是键值对Map,直接用response.body["access_token"]会触发类型错误。

解决步骤

  1. 导入Dart的JSON解析工具包dart:convert;
  2. 将响应体的字符串解析为Map<String, dynamic>类型;
  3. 从解析后的Map中读取access_token字段。

修改后的完整代码

import 'dart:convert'; // 必须导入JSON解析包
import 'package:http/http.dart' as http;

// ... 你的其他业务代码 ...

final response = await http.post(
  Uri.parse('https://login.microsoft.com/code/oauth2/token'),
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
  body: {
    "grant_type": "client_credentials",
    "client_id": "client-id",
    "client_secret": "client secret",
    "resource": "https://graph.microsoft.com"
  },
);

if (response.statusCode == 200) {
  try {
    // 把JSON字符串解析成键值对Map
    final Map<String, dynamic> tokenData = jsonDecode(response.body);
    // 提取access_token
    final String? accessToken = tokenData['access_token'];
    
    if (accessToken != null) {
      print('获取到access_token: $accessToken');
      // 这里可以继续处理token逻辑
    } else {
      print('响应数据中未找到access_token字段');
    }
  } catch (e) {
    print('JSON解析失败: $e');
  }
} else {
  print('请求失败,状态码: ${response.statusCode}');
}

额外提示

  • 必须加try-catch捕获解析异常,避免因响应格式不符合预期导致程序崩溃;
  • 用String?类型接收access_token,可以提前处理字段不存在的空值场景。

内容的提问来源于stack exchange,提问作者Sumchans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:40:29