BuildRequest<T> class
BuildRequest - 网络请求构建器 / Network Request Builder
author: zhengzaihong email: 1096877329@qq.com date: 2025-08-12
============================================================================ 类说明 / Class Description
BuildRequest 是 RxNet Plus 的核心请求构建器,提供流畅的 API 来配置和执行网络请求。 它将请求配置与 RxNet 主类分离,使代码更加清晰和易于维护。
BuildRequest is the core request builder of RxNet Plus, providing a fluent API to configure and execute network requests. It separates request configuration from the main RxNet class, making the code clearer and easier to maintain.
============================================================================ 版本历史 / Version History
📦 Version 0.6.0 (2026-04-20) - 适配器架构支持 / Adapter Architecture Support
🎯 核心变更 / Core Changes:
-
适配器集成 / Adapter Integration
- 重构为使用 NetworkAdapter 接口
- Refactored to use NetworkAdapter interface
- 支持多种网络库(Dio、http、自定义)
- Support for multiple network libraries (Dio, http, custom)
-
统一的取消令牌 / Unified Cancel Token
- 使用 RxNet 的 CancelToken 替代 Dio 的 CancelToken
- Use RxNet's CancelToken instead of Dio's CancelToken
- 跨适配器的取消支持
- Cross-adapter cancellation support
-
改进的拦截器支持 / Improved Interceptor Support
- 拦截器通过适配器执行
- Interceptors executed through adapters
- 支持请求、响应、错误拦截
- Support for request, response, and error interception
📦 Version 0.5.0 (2025-10-03) - API 优化 / API Optimization
🎯 核心改进 / Core Improvements:
-
参数类型明确化 / Explicit Parameter Types
- 引入 RequestBodyType 枚举
- Introduced RequestBodyType enum
- 分离路径参数、查询参数、Body 参数
- Separated path params, query params, and body params
-
RESTful 自动检测 / RESTful Auto-Detection
- 自动识别路径中的 {placeholder}
- Automatically recognize {placeholder} in paths
- 无需手动调用 setRestfulUrl(true)
- No need to manually call setRestfulUrl(true)
-
请求体类型清晰化 / Clear Request Body Types
- asJson() - JSON 格式
- asFormData() - FormData 格式
- asUrlEncoded() - URL 编码格式
-
改进的缓存键生成 / Improved Cache Key Generation
- 更智能的缓存键生成逻辑
- Smarter cache key generation logic
- 支持忽略特定参数
- Support for ignoring specific parameters
-
统一的错误处理 / Unified Error Handling
- 标准化的异常类型
- Standardized exception types
- 更清晰的错误信息
- Clearer error messages
📦 Version 0.4.x - 初始版本 / Initial Version
- 基础请求功能 / Basic request functionality
- 缓存支持 / Cache support
- 重试和轮询 / Retry and polling
- JSON 转换 / JSON conversion
============================================================================ 使用示例 / Usage Examples
- 基础 GET 请求 / Basic GET Request:
final result = await RxNet.get()
.setPath("/api/users")
.request();
- RESTful 请求 / RESTful Request:
final result = await RxNet.get()
.setPath("/api/users/{id}/posts")
.setPathParam("id", "123")
.setQueryParam("page", 1)
.request();
- POST JSON 数据 / POST JSON Data:
final result = await RxNet.post()
.setPath("/api/user")
.setBodyParams({"name": "John", "age": 25})
.asJson()
.request();
- 文件上传 / File Upload:
final file = await MultipartFile.fromFile("path/to/file.jpg");
final result = await RxNet.post()
.setPath("/api/upload")
.setBodyParam("file", file)
.asFormData()
.request();
- 带缓存的请求 / Request with Cache:
final result = await RxNet.get()
.setPath("/api/data")
.setCacheMode(CacheMode.FIRST_USE_CACHE_THEN_REQUEST)
.setCacheInvalidationTime(60000) // 60 seconds
.request();
- 带重试的请求 / Request with Retry:
final result = await RxNet.get()
.setPath("/api/data")
.setRetryCount(3, interval: Duration(seconds: 2))
.request();
- 取消请求 / Cancel Request:
final cancelToken = CancelToken();
RxNet.get()
.setPath("/api/data")
.setCancelToken(cancelToken)
.request();
// Later...
cancelToken.cancel("User cancelled");
============================================================================ 参数类型说明 / Parameter Types
-
路径参数 / Path Parameters (setPathParam/setPathParams)
- 用于 RESTful URL 中的占位符替换
- Used for placeholder replacement in RESTful URLs
- 例如:/users/{id} -> /users/123
- Example: /users/{id} -> /users/123
-
查询参数 / Query Parameters (setQueryParam/setQueryParams)
- 拼接在 URL 后面的参数
- Parameters appended to the URL
- 例如:/users?page=1&size=20
- Example: /users?page=1&size=20
-
Body 参数 / Body Parameters (setBodyParam/setBodyParams)
- POST/PUT/PATCH 请求的请求体参数
- Request body parameters for POST/PUT/PATCH
- 根据 bodyType 决定编码方式
- Encoding method determined by bodyType
-
原始 Body / Raw Body (setRawBody)
- 自定义的原始请求体数据
- Custom raw request body data
- 优先级高于 bodyParams
- Takes precedence over bodyParams
============================================================================ 请求体类型 / Request Body Types
- RequestBodyType.auto - 自动判断(默认)/ Auto-detect (default)
- RequestBodyType.json - JSON 格式 / JSON format
- RequestBodyType.formData - FormData 格式 / FormData format
- RequestBodyType.urlEncoded - URL 编码 / URL-encoded
- RequestBodyType.query - 查询参数 / Query parameters
============================================================================ 缓存模式 / Cache Modes
- ONLY_REQUEST - 仅请求网络 / Network only
- FIRST_USE_CACHE_THEN_REQUEST - 先缓存后网络 / Cache first, then network
- REQUEST_FAILED_READ_CACHE - 请求失败读缓存 / Read cache on failure
- CACHE_EMPTY_OR_EXPIRED_THEN_REQUEST - 缓存为空或过期时请求 / Request when cache is empty or expired
- ONLY_CACHE - 仅读缓存 / Cache only
============================================================================ 注意事项 / Notes
-
BuildRequest 实例是一次性的,每次请求都会创建新实例 BuildRequest instances are disposable, a new instance is created for each request
-
参数设置方法可以链式调用 Parameter setting methods can be chained
-
请求执行后,BuildRequest 实例不应被重用 After request execution, BuildRequest instances should not be reused
-
缓存功能在 Web 平台不可用 Cache functionality is not available on Web platform
============================================================================
Constructors
- BuildRequest(HttpMethod _HttpMethod, RxNet _rxNet)
Properties
- checkNetWork ↔ CheckNetWork?
-
getter/setter pair
- hashCode → int
-
The hash code for this object.
no setterinherited
- onResponse ↔ dynamic Function(AdapterResponse response)?
-
getter/setter pair
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
addHeaders(
Map< String, dynamic> headers) → BuildRequest<T> -
addParams(
Map< String, dynamic> params) → BuildRequest<T> - 兼容旧API:addParams
-
asFormData(
) → BuildRequest< T> - 使用FormData格式发送(multipart/form-data)
-
asJson(
) → BuildRequest< T> - 使用JSON格式发送(application/json)
-
asUrlEncoded(
) → BuildRequest< T> - 使用URL编码格式发送(application/x-www-form-urlencoded)
-
breakPointDownload(
{required String savePath, ProgressCallback? onReceiveProgress, Success? success, Failure? failure, Completed? completed, dynamic cancelCallback()?}) → void - 断点下载
-
breakPointUpload(
{required String filePath, ProgressCallback? onSendProgress, Success? success, Failure? failure, Completed? completed, dynamic cancelCallback()?, int? start}) → void - 断点上传
-
download(
{required String savePath, ProgressCallback? onReceiveProgress, Success? success, Failure? failure, Completed? completed}) → void - 下载文件
-
execute<
T> ({Success< T> ? success, Failure? failure, Completed? completed}) → void - 使用回调的方式
-
executeStream<
T> () → Stream< RxResult< T> > - Stream方式(支持轮询)
-
getCancelToken(
) → CancelToken? -
getContentLength(
AdapterResponse response) → Future< String?> - 获取内容长度(兼容方法)
-
getParams(
ParamCallBack callBack) → BuildRequest< T> -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
removeNullValueKeys(
) → BuildRequest< T> -
request<
T> () → Future< RxResult< T> > - async/await方式
-
setBodyParam(
String key, dynamic value) → BuildRequest< T> - 设置Body参数(用于POST/PUT/PATCH)
-
setBodyParams(
Map< String, dynamic> params) → BuildRequest<T> - 批量设置Body参数
-
setBodyType(
RequestBodyType type) → BuildRequest< T> - 设置请求体类型
-
setCacheInvalidationTime(
int millisecond) → BuildRequest< T> -
setCacheMode(
CacheMode cacheMode) → BuildRequest< T> -
setCancelToken(
dynamic cancelToken) → BuildRequest< T> - 设置取消令牌
-
setCheckNetwork(
CheckNetWork checkNetWork) → BuildRequest< T> -
setContentType(
String type) → BuildRequest< T> -
setEnableGlobalHeader(
bool enable) → BuildRequest< T> -
setHeader(
String key, dynamic value) → BuildRequest< T> -
setIgnoreCacheKey(
String key) → BuildRequest< T> -
setIgnoreCacheKeys(
List< String> keys) → BuildRequest<T> -
setJsonConvert(
JsonTransformation convert) → BuildRequest< T> -
setLoop(
bool loop, {Duration? interval}) → BuildRequest< T> -
setParam(
String key, dynamic value) → BuildRequest< T> - 兼容旧API:setParam - 根据HTTP方法自动判断参数类型
-
setParams(
Map< String, dynamic> params) → BuildRequest<T> - 兼容旧API:setParams
-
setPath(
String path) → BuildRequest< T> -
setPathParam(
String key, dynamic value) → BuildRequest< T> - 设置路径参数(用于RESTful风格) 例如:setPathParam("id", "123") 会将 /user/{id} 替换为 /user/123
-
setPathParams(
Map< String, dynamic> params) → BuildRequest<T> - 批量设置路径参数
-
setQueryParam(
String key, dynamic value) → BuildRequest< T> - 设置查询参数(拼接在URL后) 例如:setQueryParam("page", 1) 会生成 ?page=1
-
setQueryParams(
Map< String, dynamic> params) → BuildRequest<T> - 批量设置查询参数
-
setRawBody(
dynamic body) → BuildRequest< T> - 设置原始Body数据(用于自定义body)
-
setReceiveTimeout(
Duration timeout) → BuildRequest< T> -
setRequestIgnoreCacheTime(
bool ignoreCache) → BuildRequest< T> -
setResponseCallBack(
dynamic responseCallBack(AdapterResponse response)) → BuildRequest< T> -
setResponseType(
ResponseType type) → BuildRequest< T> -
setRestfulUrl(
bool restful) → BuildRequest< T> - 兼容旧API:setRestfulUrl 新版本会自动检测路径中的占位符,无需手动设置
-
setRetryCount(
int count, {Duration? interval}) → BuildRequest< T> -
setSendTimeout(
Duration timeout) → BuildRequest< T> -
toBodyData(
) → BuildRequest< T> - 兼容旧API:toBodyData
-
toFormData(
) → BuildRequest< T> - 兼容旧API:toFormData
-
toString(
) → String -
A string representation of this object.
inherited
-
toUrlEncoded(
) → BuildRequest< T> - 兼容旧API:toUrlEncoded
-
upload(
{ProgressCallback? onSendProgress, Success? success, Failure? failure, Completed? completed}) → void - 上传文件
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited