HTTP 请求与 JSON
学习向 REST API 发送 HTTP GET、POST、PUT 和 DELETE 请求,并将 JSON 响应解析为 Dart 对象。
HTTP 请求与 JSON 是 CoddyKit 上的免费 Flutter Mobile Development 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flutter Mobile Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flutter Mobile Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Connect to the Web!
Modern mobile apps constantly interact with the internet to fetch and send data. This is often done using HTTP requests to communicate with web services, also known as APIs (Application Programming Interfaces).
APIs provide a way for different software systems to talk to each other. For example, a weather app uses an API to get the latest forecast.
Get the `http` Package
In Flutter and Dart, the easiest way to make HTTP requests is by using the official http package. First, you need to add it to your project's pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
http: ^1.2.0 # Add this lineMaking a GET Request
After adding the package, import it into your Dart file. The most common request is GET, used to retrieve data from a server. Let's fetch some dummy post data from a public API:
import 'package:http/http.dart' as http;
import 'dart:convert'; // Needed for JSON
void main() async {
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
var response = await http.get(url);
if (response.statusCode == 200) {
print('Response body: ${response.body}');
} else {
print('Request failed with status: ${response.statusCode}.');
}
}What is JSON?
Most web APIs return data in JSON (JavaScript Object Notation) format. It's a lightweight, human-readable way to organize data.
JSON data looks like key-value pairs, similar to Dart maps. Here's what our previous GET request might return:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere...",
"body": "quia et suscipit..."
}Parsing JSON to Dart
To work with JSON data in Dart, we need to decode it. Dart's dart:convert library provides the jsonDecode() function, which converts a JSON string into a Dart Map.
Let's update our GET example to parse the response:
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() async {
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
var response = await http.get(url);
if (response.statusCode == 200) {
var jsonBody = jsonDecode(response.body);
print('User ID: ${jsonBody['userId']}');
print('Title: ${jsonBody['title']}');
} else {
print('Request failed with status: ${response.statusCode}.');
}
}Structured Data with Models
While using Map is okay for simple cases, creating a dedicated Dart model class for your JSON data offers better type safety and code readability.
A common pattern is to have a factory constructor that takes a JSON map and creates an instance of your model.
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({required this.userId, required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'] as int,
id: json['id'] as int,
title: json['title'] as String,
body: json['body'] as String,
);
}
}Fetching Data into a Model
Now, let's combine our GET request, JSON decoding, and the Post model to fetch a post and convert it into a strongly-typed Dart object. This makes accessing data much safer and clearer!
import 'package:http/http.dart' as http;
import 'dart:convert';
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({required this.userId, required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'] as int,
id: json['id'] as int,
title: json['title'] as String,
body: json['body'] as String,
);
}
}
void main() async {
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
var response = await http.get(url);
if (response.statusCode == 200) {
var jsonBody = jsonDecode(response.body);
Post post = Post.fromJson(jsonBody);
print('Fetched Post ID: ${post.id}');
print('Post Title: ${post.title}');
} else {
print('Failed to load post: ${response.statusCode}.');
}
}Sending Data with POST
To send new data to a server, you typically use a POST request. This involves providing a request body, usually in JSON format. Remember to set the 'Content-Type' header!
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() async {
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
var response = await http.post(
url,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': 'foo',
'body': 'bar',
'userId': '1',
}),
);
if (response.statusCode == 201) { // 201 Created
print('Created Post: ${response.body}');
} else {
print('Failed to create post: ${response.statusCode}.');
}
}Updating & Deleting Data
Besides GET and POST, you'll also encounter PUT and DELETE requests:
- PUT: Used to update an existing resource on the server. Similar to POST, it typically includes a request body.
- DELETE: Used to remove a resource from the server. It usually doesn't require a request body.
The http package provides http.put() and http.delete() functions, used similarly to http.post() and http.get() respectively.
Robust Request Handling
Network requests can fail for many reasons (no internet, server down, invalid data). Always prepare for these scenarios:
- Use
try-catchfor network-related exceptions (e.g.,SocketException). - Check
response.statusCodeto understand the server's reply (e.g.,200 OK,404 Not Found,500 Server Error).
This ensures your app remains stable even when things go wrong.
HTTP Request Check
Which HTTP method(s) are typically used to send new data to a server and retrieve existing data from a server, respectively?
Recap: HTTP & JSON
Great job! You've learned the fundamentals of making HTTP requests and handling JSON data:
- The
httppackage is essential for network calls. - GET retrieves data, POST sends new data, PUT updates, and DELETE removes data.
- JSON is the standard format for API data.
- Use
dart:converttojsonDecoderesponses andjsonEncoderequest bodies. - Dart model classes improve type safety and organization.
Next, you'll dive deeper into handling errors robustly in asynchronous operations!
常见问题解答
「HTTP 请求与 JSON」课时是免费的吗?
是的 — 「HTTP 请求与 JSON」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flutter Mobile Development 课程的其余内容,请升级到 CoddyKit PRO。 Flutter Mobile Development 课程共包含 4 节课。
「HTTP 请求与 JSON」这节课中我会学到什么?
学习向 REST API 发送 HTTP GET、POST、PUT 和 DELETE 请求,并将 JSON 响应解析为 Dart 对象。 你通过在浏览器中直接运行的动手代码来练习 Flutter Mobile Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Flutter Mobile Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Flutter Mobile Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「HTTP 请求与 JSON」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Flutter Mobile Development 课中编写并运行代码吗?
能。每节 Flutter Mobile Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Future 与异步等待
- HTTP 请求与 JSON
- 异步操作中的错误处理
- 流与响应式数据