• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.request.cacheDownload (缓存下载)
2<!--Kit: Basic Services Kit-->
3<!--Subsystem: Request-->
4<!--Owner: @huaxin05-->
5<!--Designer: @hu-kai45-->
6<!--Tester: @murphy1984-->
7<!--Adviser: @zhang_yixin13-->
8
9request部件主要给应用提供上传下载文件、后台传输代理的基础能力。
10
11- request的cacheDownload子组件主要给应用提供应用资源提前缓存的基础能力。
12
13- cacheDownload组件使用HTTP协议进行数据下载,并将数据资源缓存至应用内存或应用沙箱目录的文件中。
14
15- 这些缓存数据可以被部分ArkUI相关组件使用(例如:Image组件),从而提升资源加载效率。请查看ArkUI组件文档确定组件是否支持该功能。
16
17> **说明:**
18>
19> 本模块首批接口从API version 18开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
20
21## 导入模块
22
23```js
24import { cacheDownload } from '@kit.BasicServicesKit';
25```
26
27## CacheDownloadOptions
28
29缓存下载的配置选项。例如:HTTP选项、传输选项、任务选项等。
30
31**系统能力**:SystemCapability.Request.FileTransferAgent
32
33| 名称   | 类型     | 只读 | 可选 | 说明                            |
34|------|--------|----|----|-------------------------------|
35| headers | Record\<string, string\> | 否  | 是 | 缓存下载任务在HTTP传输时使用的请求头。 |
36
37## ResourceInfo<sup>20+</sup>
38
39预下载的资源信息。
40
41**系统能力**:SystemCapability.Request.FileTransferAgent
42
43| 名称   | 类型     | 只读 | 可选 | 说明                            |
44|------|--------|----|----|-------------------------------|
45| size | number | 是  | 否  | 预下载资源解压后的大小。整数值不为-1时表示资源下载成功。 |
46
47## NetworkInfo<sup>20+</sup>
48
49预下载的网络信息。
50
51**系统能力**:SystemCapability.Request.FileTransferAgent
52
53| 名称         | 类型       | 只读 | 可选 | 说明                |
54|------------|----------|----|----|-------------------|
55| dnsServers | string[] | 是  | 否  | 下载资源时使用的DNS服务器列表。 |
56
57## PerformanceInfo<sup>20+</sup>
58
59预下载的性能信息。
60
61**系统能力**:SystemCapability.Request.FileTransferAgent
62
63| 名称               | 类型     | 只读 | 可选 | 说明                            |
64|------------------|--------|----|----|-------------------------------|
65| dnsTime          | number | 是  | 否  | 从启动到dns解析完成所需的时间,单位:毫秒(ms)。   |
66| connectTime      | number | 是  | 否  | 从启动到tcp连接完成所需的时间,单位:毫秒(ms)。   |
67| tlsTime          | number | 是  | 否  | 从启动到tls连接完成所需的时间,单位:毫秒(ms)。   |
68| firstSendTime    | number | 是  | 否  | 从启动到开始发送第一个字节所需的时间,单位:毫秒(ms)。 |
69| firstReceiveTime | number | 是  | 否  | 从启动到接收第一个字节所需的时间,单位:毫秒(ms)。   |
70| totalTime        | number | 是  | 否  | 从启动到完成请求所需的时间,单位:毫秒(ms)。      |
71| redirectTime     | number | 是  | 否  | 从启动到完成所有重定向步骤所需的时间,单位:毫秒(ms)。 |
72
73## DownloadInfo<sup>20+</sup>
74
75预下载的下载信息。
76
77**系统能力**:SystemCapability.Request.FileTransferAgent
78
79| 名称          | 类型                                    | 只读 | 可选 | 说明        |
80|-------------|---------------------------------------|----|----|-----------|
81| resource    | [ResourceInfo](#resourceinfo20)       | 是  | 否  | 预下载的资源信息。 |
82| network     | [NetworkInfo](#networkinfo20)         | 是  | 否  | 预下载的网络信息。 |
83| performance | [PerformanceInfo](#performanceinfo20) | 是  | 否  | 预下载的性能信息。 |
84
85## cacheDownload.download
86
87download(url: string, options: CacheDownloadOptions): void
88
89启动一个缓存下载任务,若传输成功,则将数据下载到内存缓存和文件缓存中。
90
91- 目标资源经过HTTP传输自动解压后的大小不能超过20971520B(即20MB),否则不会保存到内存缓存或文件缓存中。
92
93- 在缓存下载数据时,如果在该url下已存在缓存内容,新的缓存内容会覆盖旧缓存内容。
94
95- 目标资源在存储到内存缓存或文件缓存中时,依照缓存下载组件的各类型缓存大小上限决定文件是否存储到指定位置,并默认使用“LRU”(最近最少使用)方式替换已有缓存内容。
96
97- 该方法为同步方法,不阻塞调用线程。
98
99**需要权限**:ohos.permission.INTERNET
100
101**系统能力**:SystemCapability.Request.FileTransferAgent
102
103**参数:**
104
105| 参数名     | 类型                                                         | 必填 | 说明                             |
106|---------|------------------------------------------------------------|----|--------------------------------|
107| url     | string                                                     | 是  | 目标资源的地址。仅支持HTTP协议,长度不超过8192字节。 |
108| options | [CacheDownloadOptions](#cachedownloadoptions) | 是  | 目标资源的缓存下载选项。                   |
109
110**错误码:**
111
112以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
113
114| 错误码ID    | 错误信息                                                                                                                                      |
115|----------|-------------------------------------------------------------------------------------------------------------------------------------------|
116| 201      | permission denied.                                                                                                              |
117| 401      | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. |
118
119**示例:**
120
121  ```ts
122  import { cacheDownload, BusinessError } from '@kit.BasicServicesKit';
123
124  // 提供缓存下载任务的配置选项。
125  let options: cacheDownload.CacheDownloadOptions = {};
126
127  try {
128    // 进行缓存下载,资源若下载成功会被缓存到应用内存或应用沙箱目录的特定文件中。
129    cacheDownload.download("https://www.example.com", options);
130  } catch (err) {
131    console.error(`Failed to download the resource. err code: ${err.code}, err message: ${err.message}`);
132  }
133  ```
134
135## cacheDownload.cancel
136
137cancel(url: string): void
138
139根据url移除一个正在执行的缓存下载任务,已保存的内存缓存和文件缓存不会受到影响。
140
141- 如果不存在对应url的任务则无其他效果。
142
143- 该方法为同步方法,不阻塞调用线程。
144
145**系统能力**:SystemCapability.Request.FileTransferAgent
146
147**参数:**
148
149| 参数名  | 类型     | 必填 | 说明                             |
150|------|--------|----|--------------------------------|
151| url  | string | 是  | 目标资源的地址。仅支持HTTP协议,长度不超过8192字节。 |
152
153**错误码:**
154
155以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
156
157| 错误码ID    | 错误信息                                                                                                                                      |
158|----------|-------------------------------------------------------------------------------------------------------------------------------------------|
159| 401      | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. |
160
161**示例:**
162
163  ```ts
164  import { cacheDownload, BusinessError } from '@kit.BasicServicesKit';
165
166  // 提供缓存下载任务的配置选项。
167  let options: cacheDownload.CacheDownloadOptions = {};
168
169  try {
170    // 进行缓存下载,资源若下载成功会被缓存到应用内存或应用沙箱目录的特定文件中。
171    cacheDownload.download("https://www.example.com", options);
172  } catch (err) {
173    console.error(`Failed to download the resource. err code: ${err.code}, err message: ${err.message}`);
174  }
175
176  // 处理其他业务逻辑。
177
178  try {
179    // 在不需要特定任务缓存时,移除缓存下载任务,已缓存的内容不受影响。
180    cacheDownload.cancel("https://www.example.com");
181  } catch (err) {
182    console.error(`Failed to cancel the task. err code: ${err.code}, err message: ${err.message}`);
183  }
184  ```
185
186## cacheDownload.setMemoryCacheSize
187
188setMemoryCacheSize(bytes: number): void
189
190设置缓存下载组件能够保存的内存缓存上限。
191
192- 使用该接口调整缓存大小时,默认使用“LRU”(最近最少使用)方式清除多余的已缓存的内存缓存内容。
193
194- 该方法为同步方法,不阻塞调用线程。
195
196**系统能力**:SystemCapability.Request.FileTransferAgent
197
198**参数:**
199
200| 参数名   | 类型     | 必填 | 说明                                      |
201|-------|--------|----|-----------------------------------------|
202| bytes | number | 是  | 设置的缓存上限。默认值为0B,最大值不超过1073741824B(即1GB)。 |
203
204**错误码:**
205
206以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
207
208| 错误码ID    | 错误信息                                                                                                                                      |
209|----------|-------------------------------------------------------------------------------------------------------------------------------------------|
210| 401      | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. |
211
212**示例:**
213
214  ```ts
215  import { cacheDownload, BusinessError } from '@kit.BasicServicesKit';
216
217  try {
218    // 设置内存缓存大小上限。
219    cacheDownload.setMemoryCacheSize(10 * 1024 * 1024);
220  } catch (err) {
221    console.error(`Failed to set memory cache size. err code: ${err.code}, err message: ${err.message}`);
222  }
223  ```
224
225## cacheDownload.setFileCacheSize
226
227setFileCacheSize(bytes: number): void
228
229设置缓存下载组件能够保存的文件缓存的上限。
230
231- 使用该接口调整缓存大小时,默认使用“LRU”(最近最少使用)方式清除多余的已缓存的文件缓存内容。
232
233- 使用该接口时,若bytes设置为0,将会删除所有缓存文件。
234
235- 该方法为同步方法,不会阻塞调用线程。
236
237**系统能力**:SystemCapability.Request.FileTransferAgent
238
239**参数:**
240
241| 参数名   | 类型     | 必填 | 说明                                                         |
242|-------|--------|----|------------------------------------------------------------|
243| bytes | number | 是  | 设置的缓存上限。默认值为104857600B(即100MB),最大值不超过4294967296B(即4GB)。 |
244
245**错误码:**
246
247以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
248
249| 错误码ID    | 错误信息                                                                                                                                      |
250|----------|-------------------------------------------------------------------------------------------------------------------------------------------|
251| 401      | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. |
252
253**示例:**
254
255  ```ts
256  import { cacheDownload, BusinessError } from '@kit.BasicServicesKit';
257
258  try {
259    // 设置文件缓存大小上限。
260    cacheDownload.setFileCacheSize(100 * 1024 * 1024);
261  } catch (err) {
262    console.error(`Failed to set file cache size. err code: ${err.code}, err message: ${err.message}`);
263  }
264  ```
265
266> ​**说明:​**​
267>
268> * 预下载模块下载的网络缓存文件会保存在应用沙箱的缓存目录中。
269> * 应用可以借助该接口的能力达成清理缓存文件的目的。
270> * 不建议应用直接对缓存目录和文件进行修改,以避免功能异常。
271
272## cacheDownload.setDownloadInfoListSize<sup>20+</sup>
273
274setDownloadInfoListSize(size: number): void
275
276设置下载信息列表的大小。
277
278- 下载信息列表用于存储预下载信息。
279
280- 下载信息和url一一对应,每次预下载都会生成一个下载信息,相同url下只会保存最新的下载信息。
281
282- 使用该接口调整列表大小时,size更新增大,列表中原有的信息不变,更新减小,默认使用“LRU”(最近最少使用)方式清除多余的已缓存信息。
283
284**系统能力**:SystemCapability.Request.FileTransferAgent
285
286**参数:**
287
288| 参数名  | 类型     | 必填 | 说明                                            |
289|------|--------|----|-----------------------------------------------|
290| size | number | 是  | 设置的下载信息列表大小。取值范围:[0, 8192],默认为0,表示不会存储任何下载信息。 |
291
292**示例:**
293
294  ```ts
295  import { cacheDownload, BusinessError } from '@kit.BasicServicesKit';
296
297  try {
298    // 设置下载信息列表大小。
299    cacheDownload.setDownloadInfoListSize(2048);
300  } catch (err) {
301    console.error(`Failed to set download information list size. err code: ${err.code}, err message: ${err.message}`);
302  }
303  ```
304
305## cacheDownload.getDownloadInfo<sup>20+</sup>
306
307getDownloadInfo(url: string): DownloadInfo | undefined
308
309基于url获取预下载的下载信息。信息存储在内存中的下载信息列表,当应用程序退出时清除。
310
311- 如果下载信息列表中能够找到指定url,返回url最近一次下载的[DownloadInfo](#downloadinfo20)。
312
313- 如果下载信息列表中找不到指定url,返回undefined。
314
315- 在缓存下载信息时,如果在该url下已存在缓存信息,新的缓存内容会覆盖旧缓存。
316
317- 目标信息在存储到内存时,使用“LRU”(最近最少使用)方式替换已有缓存内容。
318
319**需要权限**:ohos.permission.GET_NETWORK_INFO
320
321**系统能力**:SystemCapability.Request.FileTransferAgent
322
323**参数:**
324
325| 参数名 | 类型     | 必填 | 说明                   |
326|-----|--------|----|----------------------|
327| url | string | 是  | 待查询的url,最大长度为8192字节。 |
328
329**返回值:**
330
331| 类型                                           | 说明                               |
332|----------------------------------------------|----------------------------------|
333| [DownloadInfo](#downloadinfo20) \| undefined | 返回对应url的下载信息,url未记录时返回undefined。 |
334
335**错误码:**
336
337以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
338
339| 错误码ID | 错误信息               |
340|-------|--------------------|
341| 201   | permission denied. |
342
343  ```ts
344  import { cacheDownload, BusinessError } from '@kit.BasicServicesKit';
345
346  try {
347    // 设置下载信息列表大小。
348    cacheDownload.setDownloadInfoListSize(2048);
349  } catch (err) {
350    console.error(`Failed to set download information list size. err code: ${err.code}, err message: ${err.message}`);
351  }
352
353  // 提供缓存下载任务的配置选项。
354  let options: cacheDownload.CacheDownloadOptions = {};
355
356  try {
357    // 进行缓存下载,资源若下载成功会被缓存到应用内存或应用沙箱目录的特定文件中。
358    cacheDownload.download("https://www.example.com", options);
359  } catch (err) {
360    console.error(`Failed to download the resource. err code: ${err.code}, err message: ${err.message}`);
361  }
362
363  // 处理其他业务逻辑。
364
365  try {
366    // 在缓存下载完成后,获取缓存下载的信息。
367    let downloadInfo = cacheDownload.getDownloadInfo("https://www.example.com");
368    if (downloadInfo == undefined) {
369      console.info(`CacheDownload get download info undefined.`);
370    } else {
371      console.info(`CacheDownload get download info : ${JSON.stringify(downloadInfo)}`);
372    }
373  } catch (err) {
374    console.error(`Failed to get download info. err code: ${err.code}, err message: ${err.message}`);
375  }
376  ```