Flutter网络请求插件requests_plus的使用
Flutter网络请求插件requests_plus的使用
requests_plus 是一个基于 Python 的 requests 模块的强大 Dart 库,用于在 Flutter 中进行 HTTP 请求。它添加了一些新功能和增强功能,使其更适用于 Dart 和 Flutter 项目。
新功能
- 表单数据支持:通过设置
bodyEncoding参数为RequestBodyEncoding.FormData来发送multipart/form-data格式的表单数据。 - HTTP 认证支持:通过
userName和password参数轻松发送 HTTP 基本认证头。 - CORS 代理:通过使用 dart_cors-proxy 代理来绕过 CORS 限制,只需指定
corsProxyUrl参数即可。
安装
在项目的 pubspec.yaml 文件中添加以下依赖:
dependencies:
requests_plus: ^4.8.2
然后运行 flutter pub get。
使用方法
首先导入库:
import 'package:requests_plus/requests_plus.dart';
发起简单的 GET 请求
var r = await Requests.get('https://google.com');
r.raiseForStatus();
String body = r.content();
Response 对象
类似于 Python 的 requests 模块,Response 对象提供了以下功能:
r.throwForStatus()- 如果响应状态码不是成功的,则抛出异常。r.raiseForStatus()- 同throwForStatus。r.statusCode- 响应状态码。r.url- 请求的 URL。r.headers- 响应头。r.success- 布尔值,表示请求是否成功。r.hasError- 布尔值,表示请求是否失败。r.bytes()- 返回响应体作为字节数组。r.content()- 返回响应体作为字符串。r.json()- 将响应体解码为 JSON 并返回结果(动态类型)。
可选参数
json- 动态对象,将被 JSON 编码并设置为请求体。body- 原始字符串,用作请求体。bodyEncoding- 默认RequestBodyEncoding.FormURLEncoded,设置content-type头。headers- 自定义客户端头的映射。timeoutSeconds- 默认 10 秒,超过该时间未收到服务器响应则抛出异常。persistCookies- 默认true,是否存储 Cookie。verify- 默认true,是否启用 SSL 验证。withCredentials- 默认false,处理 Cookies、授权头或 TLS 客户端证书。userName- 默认null,用于 HTTP 基本认证。password- 默认null,用于 HTTP 基本认证。
注意:只能在一个请求中使用 body 或 json 其中之一。
类方法
.clearStoredCookies(url)- 清除存储的 Cookie。.setStoredCookies(url, CookieJar)- 设置存储的 Cookie。.getStoredCookies(url)- 返回存储的 Cookie。.addCookie(url, name, value)- 添加 Cookie 到 CookieJar。
示例 Demo
HTTP POST 请求
var r = await Requests.post(
'https://reqres.in/api/users',
body: {
'userId': 10,
'id': 91,
'title': 'aut amet sed',
},
bodyEncoding: RequestBodyEncoding.FormURLEncoded);
r.raiseForStatus();
dynamic json = r.json();
print(json!['id']);
忽略自签名 SSL 证书
var r = await Requests.get('https://expired.badssl.com/', verify: false);
r.raiseForStatus();
使用 Google Books API 搜索书籍示例
import 'dart:developer';
import 'package:requests_plus/requests_plus.dart';
void main(List<String> arguments) async {
const url = 'https://www.googleapis.com/books/v1/volumes?q=requests';
final response = await RequestsPlus.get(url);
if (response.statusCode == 200) {
final jsonResponse = response.json();
final itemCount = jsonResponse['totalItems'];
log('Number of books about requests: $itemCount.');
} else {
log('Request failed with status: ${response.statusCode}');
}
}
更多示例可以参考 GitHub 上的示例代码。
更多关于Flutter网络请求插件requests_plus的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter网络请求插件requests_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用Flutter网络请求插件requests_plus的示例代码。这个插件是对dio库的一个封装,提供了更简洁的API来进行HTTP请求。
首先,确保你已经在pubspec.yaml文件中添加了requests_plus依赖:
dependencies:
flutter:
sdk: flutter
requests_plus: ^x.y.z # 请替换为最新版本号
然后,运行flutter pub get来安装依赖。
接下来,是一个简单的示例,展示如何使用requests_plus进行GET和POST请求。
import 'package:flutter/material.dart';
import 'package:requests_plus/requests_plus.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String? responseData;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Requests+ Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () async {
// GET 请求示例
try {
var response = await Requests.get('https://jsonplaceholder.typicode.com/posts/1');
setState(() {
responseData = response.data.toString();
});
} catch (e) {
setState(() {
responseData = 'Error: ${e.message}';
});
}
},
child: Text('Perform GET Request'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
// POST 请求示例
var body = {
'title': 'foo',
'body': 'bar',
'userId': 1,
};
try {
var response = await Requests.post('https://jsonplaceholder.typicode.com/posts', data: body);
setState(() {
responseData = response.data.toString();
});
} catch (e) {
setState(() {
responseData = 'Error: ${e.message}';
});
}
},
child: Text('Perform POST Request'),
),
SizedBox(height: 20),
Text(responseData ?? 'No data'),
],
),
),
),
);
}
}
代码解释
-
依赖安装:
- 在
pubspec.yaml中添加requests_plus依赖,并运行flutter pub get。
- 在
-
导入包:
- 在你的Dart文件中导入
requests_plus包。
- 在你的Dart文件中导入
-
GET 请求:
- 使用
Requests.get方法发送GET请求。这个请求访问https://jsonplaceholder.typicode.com/posts/1,并尝试解析响应数据。 - 如果请求成功,将响应数据存储在
responseData变量中。 - 如果请求失败,捕获异常并显示错误信息。
- 使用
-
POST 请求:
- 使用
Requests.post方法发送POST请求。这个请求访问https://jsonplaceholder.typicode.com/posts,并附带一个JSON格式的请求体。 - 如果请求成功,将响应数据存储在
responseData变量中。 - 如果请求失败,捕获异常并显示错误信息。
- 使用
-
UI 更新:
- 使用
setState方法来更新UI,显示请求结果或错误信息。
- 使用
这样,你就可以在Flutter应用中使用requests_plus插件来发送HTTP请求了。记得根据实际需求调整请求的URL和请求体。

