📅  最后修改于: 2023-12-03 14:59:21.417000             🧑  作者: Mango
APIClient.dart 是一款基于 Dart 语言开发的 HTTP 客户端库,旨在帮助开发者在 Flutter 或其他 Dart 应用程序中发送请求并消费 HTTP API。
它使用类似于 jQuery 的 API,并且也对功能进行了扩展,以便于向后端发送各种类型的请求,并能够方便地处理响应数据。APIClient.dart 还支持一些高级特性,如中间件、拦截器等,这些能够帮助您在应用之间共享或重用代码。
APIClient.dart 可以与任何支持 Dart 的应用程序一起使用,如 Flutter、Dart VM、Aqua、Mojave 等等。它还提供了易于使用的 API,支持各种 HTTP 请求类型,并能够自动处理请求数据的序列化和反序列化。
final apiClient = APIClient();
final response = await apiClient.get('https://www.example.com/api/users');
print(response.statusCode);
print(response.body);
final apiClient = APIClient();
final response = await apiClient.post(
'https://www.example.com/api/users',
body: {'username': 'john.doe', 'password': 'password'},
);
print(response.statusCode);
print(response.body);
final apiClient = APIClient();
final file = File('path/to/file.txt');
final response = await apiClient.post(
'https://www.example.com/api/upload',
files: [file],
);
print(response.statusCode);
print(response.body);
final apiClient = APIClient();
apiClient.interceptors.add((request) async {
final token = await getToken();
request.headers['Authorization'] = 'Bearer $token';
return request;
});
final response = await apiClient.get('https://www.example.com/api/users');
print(response.statusCode);
print(response.body);
class MyMiddleware extends APIClientMiddleware {
@override
Future<APIClientRequest> handleRequest(APIClientRequest request) async {
final token = await getToken();
request.headers['Authorization'] = 'Bearer $token';
return request;
}
}
final apiClient = APIClient();
apiClient.middleware.add(MyMiddleware());
final response = await apiClient.get('https://www.example.com/api/users');
print(response.statusCode);
print(response.body);
在 pubspec.yaml
中添加以下依赖:
dependencies:
api_client_dart: ^1.0.0