仓颉 OpenHarmony 应用开发:ohos.request(上传下载)文件传输代理 API 完全指南
仓颉 OpenHarmony 应用开发:ohos.request(上传下载)文件传输代理 API 完全指南
本篇基于 CangjieCorpus 语料库中的官方 API 参考文档 cj-apis-request-agent.md,系统讲解仓颉(Cangjie)语言在 OpenHarmony 下通过 ohos.request 模块实现文件上传下载的能力:任务创建与队列管理、任务查询与条件检索、任务全生命周期控制(start/stop/pause/resume)、事件订阅与进度监听,以及 Config、Filter、FormItem、FileSpec、TaskInfo 等核心数据结构的完整字段语义。读完本文,你可以在仓颉模板工程中独立完成一个具备断点续传、网络策略控制与进度回调的后台上传下载功能。
模块概述与使用说明
ohos.request 模块给应用提供上传下载文件、后台代理传输的基础功能,底层系统能力为 SystemCapability.Request.FileTransferAgent,全部 API 自起始版本 22 开始支持。模块通过如下方式导入:
import kit.BasicServicesKit.*
使用本模块需要在应用配置中声明网络权限:
- ohos.permission.INTERNET
官方文档中的 API 示例代码遵循统一的使用约定(详见仓颉示例代码说明):
- 若示例代码首行有
// index.cj注释,表示该示例可在仓颉模板工程的index.cj文件中编译运行; - 若示例需获取 Context 应用上下文,则需在仓颉模板工程的
main_ability.cj文件中进行配置。
本文所有示例均采用 // main_ability.cj 约定,通过 Global.abilityContext 获取 UIAbilityContext,并使用 kit.PerformanceAnalysisKit.Hilog 输出日志。
任务状态机:理解 State 枚举
理解上传下载代理 API 的前提,是先理解任务(Task)在系统中经历的状态。State 枚举定义了任务当前的 9 种状态,父类型为 ToString:
public enum State <: ToString {
| Initialized
| Waiting
| Running
| Retrying
| Paused
| Stopped
| Completed
| Failed
| Removed
}
| 状态 | 语义 |
|---|---|
Initialized |
表示通过配置信息(Config)创建的任务已初始化 |
Waiting |
表示任务缺少运行或重试的资源,又或是网络状态不匹配 |
Running |
表示任务正在运行中 |
Retrying |
表示任务至少失败一次,现在正在再次处理中 |
Paused |
表示任务暂停,通常后续会恢复任务 |
Stopped |
表示任务停止 |
Completed |
表示任务完成 |
Failed |
表示任务失败 |
Removed |
表示任务移除 |
从源码结构看,任务的生命周期主线为:create() 创建后进入 Initialized,start() 后进入 Waiting(资源/网络不满足)或 Running;pause()/stop() 分别进入 Paused/Stopped 且可被 resume()/start() 恢复;后台任务失败重试时处于 Retrying;终态为 Completed、Failed,或被 remove() 置为 Removed。后续各控制接口允许调用的状态约束(对应错误码 21900007)均可据此状态机推导。
任务创建:create 函数与 Config 配置类
func create(UIAbilityContext, Config)
public func create(context: UIAbilityContext, config: Config): Task
功能:创建需要上传或下载的任务,并将其排入队列。支持 HTTP/HTTPS 协议,每个应用最多支持创建 10 个未完成的任务。
需要权限:ohos.permission.INTERNET
参数:
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| context | UIAbilityContext | 是 | - | 基于应用程序的上下文 |
| config | Config |
是 | - | 上传/下载任务的配置信息 |
返回值:Task 对象,里面包括任务 id 和任务的配置信息。
异常:BusinessException,对应错误码详见上传下载错误码与通用错误码说明文档:
| 错误码 ID | 错误信息 |
|---|---|
| 201 | Permission denied. |
| 13400001 | Invalid file or file system error. |
| 13400003 | Task service ability error. |
| 13499999 | Other error. |
| 21900004 | the application task queue is full. |
| 21900005 | Operation with wrong task mode. |
示例(创建一个后台下载任务):
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let context = Global.abilityContext
let config = Config(
Action.Download,
"https://example.com/file.txt"
)
let task = create(context, config)
Hilog.info(0, "test", "成功创建任务,任务ID: ${task.tid}")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
class Config:任务配置的完整字段
Config 是上传/下载任务的配置载体,也是本模块最核心的数据结构。其类定义为:
public class Config {
public var action: Action
public var url: String
public var title:?String
public var description: String
public var mode: Mode
public var overwrite: Bool
public var method:?String
public var headers: HashMap<String, String>
public var data:?ConfigData
public var saveas:String
public var network: Network
public var metered: Bool
public var roaming: Bool
public var retry: Bool
public var redirect: Bool
public var index: UInt32
public var begins: Int64
public var ends: Int64
public var gauge: Bool
public var precise: Bool
public var token: ?String
public var priority: UInt32
public var extras: HashMap<String, String>
}
各字段语义如下(均可读写):
| 字段 | 类型 | 默认值 | 语义 |
|---|---|---|---|
action |
Action |
- | 任务操作选项:Upload 表示上传任务,Download 表示下载任务 |
url |
String |
- | 资源地址,最大长度 8192 个字符,支持 HTTP 拦截功能 |
title |
?String |
None |
任务标题,最大 256 个字符;缺省值为小写的 upload 或 download,与 action 保持一致 |
description |
String |
"" |
任务的详细信息,最大 1024 个字符 |
mode |
Mode |
Mode.Background |
任务模式。下载到用户文件场景必须为 Mode.Foreground |
overwrite |
Bool |
false |
下载过程中路径已存在时的处理:true 覆盖已存在文件,false 下载失败。下载到用户文件场景必须为 true;设为 true 时不建议创建多个任务同时往同一文件下载,会导致文件内容混乱 |
method |
?String |
None |
HTTP 标准方法,包括 GET、POST 和 PUT,不区分大小写。上传时使用 PUT 或 POST,默认 PUT;下载时使用 GET 或 POST,默认 GET |
headers |
HashMap<String,String> |
空表 | 添加要包含在任务中的 HTTP 协议标志头。上传请求默认 Content-Type 为 multipart/form-data;下载请求默认 Content-Type 为 application/json |
data |
?ConfigData |
None |
下载时为字符串类型,通常使用 json 格式(object 将被转换为 json 文本);上传时为表单项数组 Array<FormItem>,创建单个任务可以上传最多 100 个文件 |
saveas |
String |
"./" |
保存下载文件的路径,格式见下文专题说明 |
network |
Network |
Network.AnyType |
网络选项,支持 WIFI 和 CELLULAR,默认 ANY(WIFI 或 CELLULAR) |
metered |
Bool |
false |
是否允许在按流量计费的网络中工作 |
roaming |
Bool |
true |
是否允许在漫游网络中工作 |
retry |
Bool |
true |
是否为后台任务启用自动重试,仅应用于后台任务 |
redirect |
Bool |
true |
是否允许重定向 |
index |
UInt32 |
0 |
任务的路径索引,通常用于任务断点续传 |
begins |
Int64 |
0 |
文件起点(闭区间),通常用于断点续传,默认从头开始传输。下载时对应 HTTP 协议中的 "Range" 选项起点;上传时为需上传文件的起点位置 |
ends |
Int64 |
-1 |
文件终点(闭区间),默认 -1 表示传输到整个文件末尾结束。下载时对应 "Range" 选项终点;上传时为需上传文件的结束位置 |
gauge |
Bool |
false |
后台任务的过程进度通知策略,仅应用于后台任务:false 仅完成或失败的通知;true 发出每个进度已完成或失败的通知 |
precise |
Bool |
false |
若为 true,在上传/下载无法获取文件大小时任务失败;若为 false,将文件大小设置为 -1 时任务继续 |
token |
?String |
None |
任务令牌,最小 8 个字节,最大 2048 个字节。查询带有 token 的任务需提供 token 并通过 touch 查询,否则无法查询到指定任务 |
priority |
UInt32 |
0 |
任务优先级:前台任务的优先级比后台任务高;模式相同时数字越小优先级越高 |
extras |
HashMap<String,String> |
空表 | 配置的附加功能 |
saveas 路径格式详解
saveas 是下载文件落盘位置的关键配置,官方支持四种路径形态:
- 相对路径:位于调用方的缓存路径下,如
"./xxx/yyy/zzz.html"、"xxx/yyy/zzz.html"; - internal 协议路径:支持
"internal://"及其子路径,internal为调用方(传入的 context)对应路径,"internal://cache"对应context.cacheDir,如"internal://cache/path/to/file.txt"; - 应用沙箱目录:只支持到
base及其子目录下,如"/data/storage/el1/base/path/to/file.txt"; - file 协议路径:支持应用文件和用户文件。应用文件必须匹配应用包名,只支持到
base及其子目录下,如"file://com.example.test/data/storage/el2/base/file.txt";用户文件必须为调用方创建好的用户文件 uri。
Config 构造器
public init(action: Action, url: String, title!: ?String = None, description!: String = "",
mode!: Mode = Mode.Background, overwrite!: Bool = false, method!: ?String = None,
headers!: HashMap<String, String> = HashMap<String, String>(), data!: ?ConfigData = None,
saveas!: String = "./", network!: Network = Network.AnyType, metered!: Bool = false,
roaming!: Bool = true, retry!: Bool = true, redirect!: Bool = true, index!: UInt32 = 0,
begins!: Int64 = 0, ends!: Int64 = -1, gauge!: Bool = false, precise!: Bool = false,
token!: ?String = None, priority!: UInt32 = 0, extras!: HashMap<String, String> = HashMap<String, String>()
)
除 action、url 为必填的位置参数外,其余均为命名参数,且默认值与上文"各字段语义"表一致。示例:
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let config = Config(
Action.Download,
"https://example.com/file.txt",
title: "示例下载任务",
description: "这是一个示例下载任务",
mode: Mode.Background,
overwrite: true,
network: Network.Wifi,
metered: false,
roaming: true,
retry: true,
redirect: true,
gauge: false,
precise: false,
priority: 0
)
Hilog.info(0, "test", "成功创建配置对象")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
任务查询与检索:getTask、show、touch、search、remove
func getTask(UIAbilityContext, String, ?String)
public func getTask(context: UIAbilityContext, id: String, token!: ?String = None): Task
功能:根据任务 id 查询任务。
参数:
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| context | UIAbilityContext | 是 | - | 基于应用程序的上下文 |
| id | String |
是 | - | 任务 id |
| token | ?String |
否 | None |
命名参数。 任务查询 token |
返回值:Task 对象,包含任务 id 和任务的配置信息。
异常:BusinessException,错误码见上传下载错误码:
| 错误码 ID | 错误信息 |
|---|---|
| 13400003 | Task service ability error. |
| 13499999 | Other error. |
| 21900006 | Task removed or not found. |
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let context = Global.abilityContext
let taskId = "example_task_id"
let task = getTask(context, taskId)
Hilog.info(0, "test", "成功获取任务,任务ID: ${task.tid}")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
func show(String)
public func show(id: String): TaskInfo
功能:根据任务 id 查询任务的详细信息。
参数:id(String,必填)——任务 id。
返回值:返回任务详细信息的 TaskInfo 对象。
异常:错误码 13400003(Task service ability error.)、21900006(Task removed or not found.)。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let taskId = "example_task_id"
let taskInfo = show(taskId)
Hilog.info(0, "test", "任务信息: ${taskInfo.description}")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
func touch(String, String)
public func touch(id: String, token: String): TaskInfo
功能:根据任务 id 和 token 查询任务的详细信息。这是查询带 token 任务的唯一途径——对应 Config.token 的语义:查询带有 token 的任务需提供 token 并通过 touch 查询,否则无法查询到指定任务。
参数:id(任务 id,必填)、token(任务查询 token,必填)。
返回值:TaskInfo 对象。
异常:错误码 13400003、21900006。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let taskId = "example_task_id"
let token = "example_token"
let taskInfo = touch(taskId, token)
Hilog.info(0, "test", "任务信息: ${taskInfo.description}")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
func search(Filter)
public func search(filter!: Filter = Filter()): Array<String>
功能:根据 Filter 过滤条件查找任务 id。
参数:
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| filter | Filter |
否 | Filter() |
过滤条件 |
返回值:Array<String>,返回满足条件的任务 id。
异常:错误码 13400003(Task service ability error.)。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let filter = Filter()
let taskIds = search(filter: filter)
Hilog.info(0, "test", "搜索到任务数量: ${taskIds.size}")
for (id in taskIds) {
Hilog.info(0, "test", "任务ID: ${id}")
}
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
class Filter:条件检索的过滤器
public class Filter {
public var before:?Int64
public var after:?Int64
public var state:?State
public var action:?Action
public var mode:?Mode
public init(before!: ?Int64 = None, after!: ?Int64 = None, state!: ?State = None,
action!: ?Action = None, mode!: ?Mode = None
)
}
各字段均为可选命名参数,全部为 None 时查询所有任务:
| 字段 | 类型 | 默认行为 | 语义 |
|---|---|---|---|
before |
?Int64 |
None |
结束的 Unix 时间戳(毫秒),默认为调用时刻 |
after |
?Int64 |
None |
开始的 Unix 时间戳(毫秒),默认值为调用时刻减 24 小时 |
state |
?State |
None |
指定任务的状态;未填写则查询所有任务 |
action |
?Action |
None |
任务操作选项;未填写则查询所有任务 |
mode |
?Mode |
None |
任务模式;未填写则查询所有任务 |
注意时间窗口的默认值:after 默认为"调用时刻减 24 小时"、before 默认为"调用时刻",即默认只检索最近 24 小时内创建的任务。TaskInfo.ctime 字段说明也印证了这一点:使用 search 查询时,任务的 ctime 需处于 [after, before] 区间内才可被检索到。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let filter = Filter(
state: State.Running,
action: Action.Download,
mode: Mode.Background
)
Hilog.info(0, "test", "成功创建过滤器对象")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
func remove(String)
public func remove(id: String): Unit
功能:移除属于调用方的指定任务,如果正在处理中,该任务将被迫停止。在调用后任务对象和其回调函数会被释放。
参数:id(String,必填)——任务 id。
异常:错误码 13400003、21900006。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let taskId = "example_task_id"
remove(taskId)
Hilog.info(0, "test", "成功移除任务,任务ID: ${taskId}")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
任务对象 Task 与生命周期控制方法
class Task
public class Task {
public let tid: String
public var config: Config
public init(tid: String, config: Config)
}
功能:上传或下载任务。使用该类前需要先获取 Task 对象,通过 create 获取。
tid(String,只读):任务 id,由系统自动生成且唯一;config(Config,可读写):任务的配置信息。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let context = Global.abilityContext
let taskId = "example_task_id"
let config = Config(
Action.Download,
"https://example.com/file.txt"
)
let task = Task(taskId, config)
Hilog.info(0, "test", "成功初始化任务,任务ID: ${task.tid}")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
启动、停止、暂停与恢复
以下四个方法共同构成任务生命周期控制,其可调用状态约束与 State 状态机一一对应,违反约束会抛出错误码 21900007(Operation with wrong task state.)。
func start()
public func start(): Unit
功能:启动一个任务。以下状态的任务可以被启动:
- 刚被
create接口创建的任务; - 使用
create接口创建的已经失败或者停止的下载任务。
需要权限:ohos.permission.INTERNET
异常:错误码 201(Permission denied.)、13400003(Task service ability error.)、21900007(Operation with wrong task state.)。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let context = Global.abilityContext
let config = Config(
Action.Download,
"https://example.com/file.txt"
)
let task = create(context, config)
task.start()
Hilog.info(0, "test", "成功启动任务")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
func stop()
public func stop(): Unit
功能:停止任务,可以停止正在运行/正在等待/正在重试的任务,已停止的任务可被 start 恢复。
异常:错误码 13400003、21900007。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let context = Global.abilityContext
let config = Config(
Action.Download,
"https://example.com/largefile.zip"
)
let task = create(context, config)
task.start()
task.stop()
Hilog.info(0, "test", "成功停止任务")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
func pause()
public func pause(): Unit
功能:暂停任务,可以暂停正在等待/正在运行/正在重试的任务,已暂停的任务可被 resume 恢复。
异常:错误码 13400003、21900007。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let config = Config(
Action.Download,
"zipURL"
)
let task = create(Global.abilityContext, config)
task.pause()
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.toString()}")
}
func resume()
public func resume(): Unit
功能:重新启动任务,可以恢复被暂停的任务。
需要权限:ohos.permission.INTERNET
异常:错误码 201、13400003、21900007。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let config = Config(
Action.Download,
"zipURL"
)
let task = create(Global.abilityContext, config)
task.resume()
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.toString()}")
}
事件订阅:on / off 与回调类型
任务事件通过 EventCallbackType 枚举区分,订阅后回调触发。EventCallbackType 父类型为 Equatable<EventCallbackType> & Hashable & ToString,并提供 ==、!= 运算符与 hashCode()、toString() 方法:
public enum EventCallbackType <: Equatable<EventCallbackType> & Hashable & ToString {
| Progress
| Completed
| Failed
| Pause
| Resume
| Remove
| Response
}
| 事件 | 语义 |
|---|---|
Progress |
任务进度,任务进度有进展时触发 |
Completed |
任务完成 |
Failed |
任务失败 |
Pause |
任务暂停 |
Resume |
任务恢复 |
Remove |
任务删除 |
Response |
任务接收到响应(响应头) |
订阅进度事件:on(EventCallbackType, Callback1Argument<Progress>)
public func on(event: EventCallbackType, callback: Callback1Argument<Progress>): Unit
功能:订阅任务进度的事件。
参数:
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| event | EventCallbackType |
是 | - | 订阅的事件类型,取值为 Progress,表示任务进度 |
| callback | Callback1Argument<Progress> |
是 | - | 发生相关事件时触发该回调方法,返回任务信息的数据结构 |
回调类需实现 Callback1Argument<T> 接口(见 callback_invoke 参考)。示例:
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
import ohos.callback_invoke.*
public class ProgressCallback2 <: Callback1Argument<Progress> {
public ProgressCallback2(let f: (Progress) -> Unit) {}
public func invoke(err: ?BusinessException, arg: Progress): Unit {
f(arg)
}
}
try {
let config = Config(
Action.Download,
"zipURL"
)
let task = create(Global.abilityContext, config)
let callback = ProgressCallback2({progress => Hilog.info(0, "test", "invoke success")})
task.on(EventCallbackType.Progress, callback)
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.toString()}")
}
订阅响应头:on(EventCallbackType, Callback1Argument<HttpResponse>)
public func on(event: EventCallbackType, callback: Callback1Argument<HttpResponse>): Unit
功能:订阅任务响应头。
参数:
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| event | EventCallbackType |
是 | - | 订阅的事件类型,取值为 Response,表示任务响应 |
| callback | Callback1Argument<HttpResponse> |
是 | - | 发生相关事件时触发该回调方法,返回任务响应头的数据结构 |
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.callback_invoke.*
import ohos.business_exception.BusinessException
public class ProgressCallback1 <: Callback1Argument<HttpResponse> {
public ProgressCallback1(let f: (HttpResponse) -> Unit) {}
public func invoke(err: ?BusinessException, arg: HttpResponse): Unit {
f(arg)
}
}
try {
let config = Config(
Action.Download,
"zipURL"
)
let task = create(Global.abilityContext, config)
let callback = ProgressCallback1({response => Hilog.info(0, "test", "invoke success")})
task.on(EventCallbackType.Response, callback)
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.toString()}")
}
取消订阅:off(EventCallbackType, ?CallbackObject)
public func off(event: EventCallbackType, callback!: ?CallbackObject = None): Unit
功能:取消订阅任务事件。
参数:
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| event | EventCallbackType |
是 | - | 订阅的事件类型(Progress/Completed/Failed/Pause/Resume/Remove/Response 均适用) |
| callback | ?CallbackObject | 否 | None |
命名参数。 需要取消订阅的回调函数;若无此参数,则取消订阅当前类型的所有回调函数 |
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
import ohos.callback_invoke.*
public class ProgressCallback <: Callback1Argument<Progress> {
public ProgressCallback(let f: (Progress) -> Unit) {}
public func invoke(err: ?BusinessException, arg: Progress): Unit {
f(arg)
}
}
try {
let config = Config(
Action.Download,
"zipURL"
)
let task = create(Global.abilityContext, config)
let callback = ProgressCallback({progress => Hilog.info(0, "test", "invoke success")})
task.on(EventCallbackType.Pause, callback)
task.off(EventCallbackType.Pause, callback: callback)
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.toString()}")
}
事件数据结构:Progress 与 HttpResponse
class Progress(任务进度)
public class Progress {
public let state: State
public let index: UInt32
public let processed: Int64
public let sizes: Array<Int64>
public let extras: HashMap<String, String>
}
| 字段 | 类型 | 语义 |
|---|---|---|
state |
State |
任务当前的状态 |
index |
UInt32 |
任务中当前正在处理的文件索引 |
processed |
Int64 |
任务中当前文件的已处理数据大小,单位为字节(B) |
sizes |
Array<Int64> |
任务中文件的大小,单位为字节(B)。在下载过程中,若服务器使用 chunk 方式传输导致无法从请求头中获取文件总大小时,sizes 为 -1 |
extras |
HashMap<String,String> |
交互的额外内容,例如来自服务器的响应的 header 和 body |
class HttpResponse(任务响应头)
public class HttpResponse {
public let version: String
public let statusCode: Int32
public let reason: String
public let headers: HashMap<String, Array<String>>
}
| 字段 | 类型 | 语义 |
|---|---|---|
version |
String |
Http 版本 |
statusCode |
Int32 |
Http 响应状态码 |
reason |
String |
Http 响应原因 |
headers |
HashMap<String, Array<String>> |
Http 响应头部 |
上传任务的数据结构:ConfigData、FormItem 与 FileSpec
上传任务通过 multipart/form-data 组织请求体,核心数据结构如下。
enum ConfigData
public enum ConfigData {
| StringValue(String)
| FormItems(Array<FormItem>)
}
上传/下载任务的 data 配置枚举类型,两个变体:
StringValue(String):下载时使用,data为字符串类型,通常使用 json(object 将被转换为 json 文本),默认为空;FormItems(Array<FormItem>):上传时使用,data是表单项数组Array<FormItem>,默认为空。
class FormItem(表单项)
public class FormItem {
public var name: String
public var value: FormItemValue
public init(name: String, value: FormItemValue)
}
任务的表单项信息:
name(String,可读写):表单参数名;value(FormItemValue,可读写):表单参数值。
两个参数均为必填的命名参数:
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| name | String |
是 | 命名参数。 表单参数名 |
| value | FormItemValue |
是 | 命名参数。 表单参数值 |
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let formItem = FormItem(
"exampleField",
FormItemValue.StringItem("exampleValue")
)
Hilog.info(0, "test", "成功创建表单项对象")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
enum FormItemValue
public enum FormItemValue {
| StringItem(String)
| FileItem(FileSpec)
| FileItemArray(Array<FileSpec>)
}
表单项的值枚举类型:
StringItem(String):表示字符串(文档原文标注为"文件路径");FileItem(FileSpec):表示单个文件信息;FileItemArray(Array<FileSpec>):表示多个文件信息。
class FileSpec(表单项的文件信息)
public class FileSpec {
public var path: String
public var mimeType:?String
public var filename:?String
public var extras: HashMap<String, String>
public init(
path: String,
mimeType!: ?String = None,
filename!: ?String = None,
extras!: HashMap<String, String> = HashMap<String, String>()
)
}
字段语义(均可读写):
path(String):文件路径,支持五种形式:- 相对路径,位于调用方的缓存路径下,例如
"./xxx/yyy/zzz.html"、"xxx/yyy/zzz.html"; - internal 协议路径,支持
"internal://"及其子路径,internal为调用方(即传入的 context)对应路径,"internal://cache"对应context.cacheDir,例如"internal://cache/path/to/file.txt"; - 应用沙箱目录,只支持到
base及其子目录下,例如"/data/storage/el1/base/path/to/file.txt"; - file 协议路径,必须匹配应用包名,只支持到
base及其子目录下,例如"file://com.example.test/data/storage/el2/base/file.txt"; - 用户公共文件,仅支持上传任务,例如
"file://media/Photo/path/to/file.img",且仅支持前台任务;
- 相对路径,位于调用方的缓存路径下,例如
mimeType(?String):文件的 mimeType,通过文件名获取,默认值为文件名后缀;filename(?String):文件名,默认值通过路径获取;extras(HashMap<String,String>):文件信息的附加内容,该参数不会体现在 HTTP 请求中。
// main_ability.cj
import kit.BasicServicesKit.*
import kit.PerformanceAnalysisKit.Hilog
import ohos.business_exception.BusinessException
try {
let fileSpec = FileSpec(
"./example.txt",
mimeType: "text/plain",
filename: "example.txt"
)
Hilog.info(0, "test", "成功创建文件规范对象")
} catch (e: BusinessException) {
Hilog.info(0, "test", "${e.message}")
}
查询结果数据结构:class TaskInfo
TaskInfo 是 show/touch 查询返回的任务信息数据结构,提供普通查询和系统查询两种字段的可见范围。全部字段只读:
public class TaskInfo {
public let saveas: String
public let url: String
public let data: ConfigData
public let tid: String
public let title: String
public let description: String
public let action: Action
public let mode: Mode
public let priority: UInt32
public let mimeType: String
public let progress: Progress
public let gauge: Bool
public let ctime: UInt64
public let mtime: UInt64
public let retry: Bool
public let tries: UInt32
public let faults: Faults
public let reason: String
public let extras: HashMap<String, String>
}
| 字段 | 类型 | 语义 |
|---|---|---|
action |
Action |
任务操作选项:Upload 上传 / Download 下载 |
ctime |
UInt64 |
创建任务的 Unix 时间戳(毫秒),由当前设备的系统生成。使用 search 查询时,该值需处于 [after, before] 区间内才可正常查询到任务 id |
data |
ConfigData |
任务值。通过 show、touch 进行查询 |
description |
String |
任务描述 |
extras |
HashMap<String,String> |
任务的额外部分 |
faults |
Faults |
任务的失败原因 |
gauge |
Bool |
后台任务的进度通知策略:false 仅完成或失败的通知;true 发出每个进度已完成或失败的通知 |
mimeType |
String |
任务配置中的 mimetype |
mode |
Mode |
任务模式:Foreground 前台 / Background 后台 |
mtime |
UInt64 |
任务状态改变时的 Unix 时间戳(毫秒),由当前设备的系统生成 |
priority |
UInt32 |
任务配置中的优先级。前台任务的优先级比后台任务高;相同模式的任务,数字越小优先级越高 |
progress |
Progress |
任务的过程进度 |
reason |
String |
等待/失败/停止/暂停任务的原因 |
retry |
Bool |
任务的重试开关,仅应用于后台任务 |
saveas |
String |
保存下载文件的路径 |
tid |
String |
任务 id |
title |
String |
任务标题 |
tries |
UInt32 |
任务的尝试次数 |
url |
String |
任务的 url。通过 show、touch 进行查询 |
模式与网络选项:Mode 和 Network 枚举
enum Mode(任务模式)
public enum Mode <: Equatable<Mode> & ToString {
| Background
| Foreground
}
功能:定义模式选项。当应用的前台任务切换到后台一段时间后会显示运行失败或暂停,而后台任务不受此操作影响。
Background:表示后台任务(Config.mode的默认值);Foreground:表示前台任务。
从文档约束可以推断出选型逻辑:下载普通资源到缓存/沙箱宜用 Background(配合 retry、gauge 等后台专属策略);而下载到用户文件场景必须使用 Foreground 且 overwrite 为 true。
enum Network(网络选项)
public enum Network <: Equatable<Network> & ToString {
| AnyType
| Wifi
| Cellular
}
功能:定义网络选项。网络不满足设置条件时,未执行的任务会等待执行,执行中的任务将失败或暂停。
AnyType:表示不限网络类型(Config.network的默认值);Wifi:表示无线网络;Cellular:表示蜂窝数据网络。
配合 metered(按流量计费)与 roaming(漫游)两个布尔开关,可精细控制任务在网络受限场景下的行为;与 State.Waiting 中"网络状态不匹配"的语义相呼应。
操作选项与失败原因:Action 和 Faults 枚举
enum Action
public enum Action <: Equatable<Action> & ToString {
| Download
| Upload
}
功能:定义操作选项。Download 表示下载任务,Upload 表示上传任务。父类型 Equatable<Action>、ToString 提供 ==/!= 相等性比较(返回值 Bool,相等/不相等分别返回 true/false)与 toString() 字符串表示。
enum Faults(任务失败原因)
public enum Faults <: ToString {
| Others
| Disconnected
| Timeout
| Protocol
| Fsio
}
| 变体 | 语义 |
|---|---|
Others |
表示其他故障 |
Disconnected |
表示网络断开连接 |
Timeout |
表示任务超时 |
Protocol |
表示协议错误,例如服务器内部错误(500)、无法处理的数据区间(416)等 |
Fsio |
表示文件系统 io 错误,例如打开/查找/读取/写入/关闭 |
Faults 通过 TaskInfo.faults 字段暴露,可用于失败后的差异化处理(如 Disconnected 可提示用户检查网络,Fsio 则应检查文件权限与路径)。
自定义系统事件:BroadcastEvent
public enum BroadcastEvent <: ToString {
| Complete
}
功能:定义自定义系统事件。用户可以使用公共事件接口获取该事件。上传下载 SA 具有 ohos.permission.SEND_TASK_COMPLETE_EVENT 权限,用户可以配置事件的 metadata 指向的二级配置文件来拦截其他事件发送者。
事件数据使用 CommonEventData 类型传输公共事件相关数据。与 CommonEventData 介绍 介绍的成员内容填写有所区别:
CommonEventData.code:表示任务的状态,目前为0x40COMPLETE 或0x41FAILED;CommonEventData.data:表示任务的 taskId。
Complete 变体表示自定义系统事件完成:在任务结束后会触发该事件,根据任务的成功或失败,事件的 code 返回 0x40 或者 0x41。
这意味着即使应用进程被系统回收,其他进程/应用仍可借助公共事件感知上传下载任务的最终结果,这是"后台代理传输"设计的关键一环。
错误码总览与排查建议
综合 上传下载错误码文档 与 通用错误码说明文档,本模块涉及的错误码及排查建议如下:
| 错误码 ID | 错误信息 | 错误描述 | 处理步骤 |
|---|---|---|---|
| 201 | Permission denied. | 权限不足(需 ohos.permission.INTERNET) |
检查应用配置中是否声明网络权限 |
| 13400001 | Invalid file or file system error. | 文件操作异常:文件权限不足或操作失败 | 检查文件权限是否合理 |
| 13400002 | Bad file path. | 文件路径异常:路径不合法或路径下文件已存在 | 检查上传下载的文件路径是否正确 |
| 13400003 | Task service ability error. | 服务异常:下载任务后台服务失败,可能原因任务创建失败 | 检查任务配置是否正确 |
| 13499999 | Other error. | 出现特殊错误 | 检查任务配置是否正确 |
| 21900004 | the application task queue is full. | 应用任务队列已满(前台任务直接抢占,不涉及工作队列) | 1. 通过查询接口获取应用所有后台任务;2. 主动清理释放配额;3. 重新创建后台任务 |
| 21900005 | Operation with wrong task mode. | 任务模式错误,如非前台应用创建前台任务 | 给前台应用注册、注销事件监听,按接口说明使用 |
| 21900006 | Task removed or not found. | 操作不存在的任务:删除、查询不存在的任务 | 1. 通过检索接口查询存在的任务;2. 确认任务存在(系统会定期清理垃圾任务);3. 使用正确的任务编号重新操作 |
| 21900007 | Operation with wrong task state. | 在不支持的状态上的操作:启动已删除/非初始化的任务、暂停非执行中的任务、恢复非暂停的任务、停止非执行中的任务 | 1. 查询任务状态;2. 执行当前状态支持的操作 |
各接口与错误码的对应关系:create(201、13400001、13400003、13499999、21900004、21900005)、getTask(13400003、13499999、21900006)、show/touch/remove(13400003、21900006)、search(13400003)、pause/stop(13400003、21900007)、start/resume(201、13400003、21900007)。
实战要点小结
- 配额意识:每个应用最多 10 个未完成任务,
create前建议先search盘点存量任务,避免触发 21900004 后被动清理; - 用户文件场景:必须
Mode.Foreground+overwrite: true,且FileSpec的用户公共文件路径仅前台任务可用; - 断点续传:通过
begins/ends(闭区间字节范围,下载映射为 HTTP Range 头)与index组合实现;precise决定文件大小不可知时是失败还是按 -1 继续; - 进度策略:仅后台任务可用
gauge(细粒度进度通知)与retry(自动重试);Progress.sizes在 chunk 传输下为 -1,UI 层需做无总长进度条降级; - 安全查询:带
token(8~2048 字节)的任务只能通过touch查询,为多应用间任务隔离提供手段; - 进程外感知:借助
BroadcastEvent.Complete公共事件(code 0x40/0x41、data 为 taskId)跨进程获取任务终态; - 状态机操作:
start/stop/pause/resume的合法调用状态见各接口说明,违规操作统一抛 21900007,建议先show查询State再操作。
以上能力与数据结构均以语料库中 cj-apis-request-agent.md 原文档为准,全部 API 起始版本 22,系统能力 SystemCapability.Request.FileTransferAgent,可在仓库同目录的 BasicServicesKit 参考资料中继续查阅电池、公共事件、设置等相邻模块的仓颉 API 参考。