Flutter中如何从接口返回结果中提取access_token值
How to Extract
access_token from Your API Response Got it, let's walk through how to pull that access_token out of the JSON response. First, you'll need to parse the raw response string into a Dart map so you can access the token by its key. Here's what you need to do:
Step 1: Add the JSON parsing import
First, make sure you have this import at the top of your Dart file to handle JSON decoding:
import 'dart:convert';
Step 2: Modify your request to parse the response
You can update your existing code in two ways—either keeping the .then() chain or switching to async/await (which is cleaner since you already marked the function as async).
Option 1: Using .then() (keeping your original structure)
Future<Null> getData() async { var url = "http://192.168.1.23:7070/api/v2/token"; http.post(url, body:{ "grant_type": "string", "branchcode": "string", "password": "string", "username": "string", "dbname": "string", "dbuser": "string", "dbpassword": "string", "dbtype": "string" }).then((response){ print("Response Status: ${response.statusCode}"); // Only parse if the request succeeded (status code 200) if (response.statusCode == 200) { // Convert the raw JSON string to a Dart Map Map<String, dynamic> jsonResponse = jsonDecode(response.body); // Extract the access_token by its key String accessToken = jsonResponse['access_token']; print("Extracted Access Token: $accessToken"); // Now you can store this token (e.g., in SharedPreferences) or use it for other requests } else { print("Request failed with status: ${response.statusCode}"); } }).catchError((error) { print("Error making request: $error"); }); }
Option 2: Using async/await (cleaner, more readable)
Since your function is already marked async, using await makes the code flow more linearly and easier to debug:
Future<Null> getData() async { try { var url = "http://192.168.1.23:7070/api/v2/token"; var response = await http.post(url, body:{ "grant_type": "string", "branchcode": "string", "password": "string", "username": "string", "dbname": "string", "dbuser": "string", "dbpassword": "string", "dbtype": "string" }); print("Response Status: ${response.statusCode}"); if (response.statusCode == 200) { Map<String, dynamic> jsonResponse = jsonDecode(response.body); String accessToken = jsonResponse['access_token']; print("Extracted Access Token: $accessToken"); // Use or store the token here } else { print("Request failed with status: ${response.statusCode}"); } } catch (error) { print("Error occurred: $error"); } }
Key Notes:
- Always check the response status code first (like
200 OK) before parsing—this avoids trying to decode error responses that might not be valid JSON. - The
jsonDecode()function converts the raw string response into aMap<String, dynamic>, which lets you access values using their JSON keys (like'access_token'). - Once you have the token, you can store it (e.g., using the
shared_preferencespackage) to reuse it in future API calls instead of requesting a new one every time.
内容的提问来源于stack exchange,提问作者Kaan Karamanoğlu
相关产品推荐
相关产品推荐

