1# Request
2
3##  Introduction
4
5### Overall Introduction
6
7The Request service provides third-party applications with the download and upload capabilities. With it, you can conveniently and efficiently use and manage download and upload services, including creating, removing, suspending, resuming, and querying download and upload tasks.
8
9### Architecture Diagram
10
11**Figure 1** Architecture of the download subsystem
12![](figures/download_architecture_en.png "Download Subsystem")
13
14System applications: dependent system applications.
15
16Third-party applications: dependent third-party applications.
17
18Download API: provides the download function.
19
20IDL: enables NAPIs to communicate with each other.
21
22Download service: creates, processes, and completes a download task upon request by a client.
23
24Data download capability: saves download records.
25
26**Figure 2** Architecture of the upload subsystem
27![](figures/subsystem_architecture_en.png "Upload Subsystem")
28
29Extended/Third-party application: a client that initiates an upload request.
30
31JS APIs: provide the upload function for external systems.
32
33Local APIs: provide the upload function for local files.
34
35Upload task: created upon request by a client for processing the upload request and forwarding the upload response from the server.
36
37Curl adaptation: encapsulates the third-party library libcurl.
38
39File acquisition: obtains the file to be uploaded based on the file path specified in the upload request.
40
41libcurl: functions as a third-party library.
42
43DataAbility capability: used to obtain files in the DataAbility file protocol path.
44
45## Directory Structure
46
47```
48/base/request/request
49├── figures                                # Architecture diagrams
50├── download/ability                       # Database management module of the download service
51├── download/etc 	                       # Process configuration files of the download service
52	 └──interfaces/kits/js/napi            # APIs that the download service provides for external systems
53		 └──download_single                # NAPIs of the download service
54├── download/sa_profile                    # System service configuration files of the download service
55├── download/services                      # Implementation of the download service
56├── download/utils                         # Constants defined for log printing and common events of the download service
57├── upload/frameworks                      # Implementation of the upload service
58├── upload/interfaces/kits                 # APIs that the upload service provides for external systems
59│   ├── js                                 # JS API definition
60│   └── napi                               # NAPIs of the upload service
61└── upload/unitest                         # Unit test of the upload service
62```
63
64##  Description
65
66###  Available APIs
67
68**Table 1** Major APIs in Request
69
70| API                                                          | Description                                                  |
71| ------------------------------------------------------------ | ------------------------------------------------------------ |
72| download(config: DownloadConfig, callback: AsyncCallback\<DownloadTask>): void | Downloads files. This API uses an asynchronous callback to return the **DownloadTask** instance. You can then use the instance to perform operations on the download task, for example, adding listeners for the **progress**, **complete**, and **fail** events, or suspending, resuming, removing, and querying the download task. |
73| download(config: DownloadConfig): Promise\<DownloadTask>     | Downloads files. This API uses a promise to return the **DownloadTask** instance. You can then use the instance to perform operations on the download task, for example, adding listeners for the **progress**, **complete**, and **fail** events, or suspending, resuming, removing, and querying the download task. |
74| upload(config: UploadConfig, callback: AsyncCallback\<UploadTask>): void | Uploads files. This API uses an asynchronous callback to return the **UploadTask** instance. You can then use the instance to perform operations on the upload task, for example, adding listeners for the **progress**, **headerReceive**, and **fail** events, or removing the upload task. |
75| upload(config: UploadConfig): Promise\<UploadTask>           | Uploads files. This API uses a promise to return the **UploadTask** instance. You can then use the instance to perform operations on the upload task, for example, adding listeners for the **progress**, **headerReceive**, and **fail** events, or removing the upload task. |
76| download(context: BaseContext,config: DownloadConfig, callback: AsyncCallback\<DownloadTask>): void | Downloads files. This API uses an asynchronous callback to return the **DownloadTask** instance. You can then use the instance to perform operations on the download task, for example, adding listeners for the **progress**, **complete**, and **fail** events, or suspending, resuming, removing, and querying the download task. |
77| download(context: BaseContext,config: DownloadConfig): Promise\<DownloadTask> | Downloads files. This API uses a promise to return the **DownloadTask** instance. You can then use the instance to perform operations on the download task, for example, adding listeners for the **progress**, **complete**, and **fail** events, or suspending, resuming, removing, and querying the download task. |
78| upload(context: BaseContext,config: UploadConfig, callback: AsyncCallback\<UploadTask>): void | Uploads files. This API uses an asynchronous callback to return the **UploadTask** instance. You can then use the instance to perform operations on the upload task, for example, adding listeners for the **progress**, **headerReceive**, and **fail** events, or removing the upload task. |
79| upload(context: BaseContext,config: UploadConfig): Promise\<UploadTask> | Uploads files. This API uses a promise to return the **UploadTask** instance. You can then use the instance to perform operations on the upload task, for example, adding listeners for the **progress**, **headerReceive**, and **fail** events, or removing the upload task. |
80
81**Table 2** Major APIs in DownloadTask
82
83| API                                                          | Description                                                  |
84| ------------------------------------------------------------ | ------------------------------------------------------------ |
85| on(type: 'progress', callback:(receivedSize: number, totalSize: number) => void): void | Enables listening for download task progress changes. This API uses a callback to return the download progress. If this API is called multiple times, the callback passed in the last call is used. |
86| on(type: 'complete' l 'pause' l 'remove', callback:() => void): void | Enables listening for download states: **complete**, **pause**, and **remove**. This API uses a callback to return the result. If this API is called multiple times, the callback passed in the last call is used. |
87| on(type: 'fail', callback:(error: number) => void): void     | Enables listening for the download failure event. This API uses a callback to return the error code. If this API is called multiple times, the callback passed in the last call is used. |
88| off(type: 'progress', callback?:(receivedSize: number, totalSize: number) => void): void | Disables listening for download task progress changes. This API uses a callback to return the result. |
89| off(type: 'complete' l 'pause' l 'remove', callback?:() => void): void | Disables listening for download states: **complete**, **pause**, and **remove**. This API uses a callback to return the result. |
90| off(type: 'fail', callback?:(error: number) => void): void   | Disables listening for the download failure event. This API uses a callback to return the result. |
91| remove(): Promise\<boolean>                                  | Removes this download task. This API uses a promise to return the result. |
92| remove(callback: AsyncCallback\<boolean>): void              | Removes this download task. This API uses an asynchronous callback to return the result. |
93| pause(): Promise\<boolean>                                   | Pauses this download task. This API uses a promise to return the result. |
94| pause(callback: AsyncCallback\<boolean>): void               | Pauses this download task. This API uses an asynchronous callback to return the result. |
95| resume(): Promise\<boolean>                                  | Resumes this download task. This API uses a promise to return the result. |
96| resume(callback: AsyncCallback\<boolean>): void              | Resumes this download task. This API uses an asynchronous callback to return the result. |
97| query(): Promise\<DownloadInfo>                              | Queries download tasks. This API uses a promise to return the **DownloadInfo** object. |
98| query(callback: AsyncCallback\<DownloadInfo>): void          | Queries download tasks. This API uses an asynchronous callback to return the **DownloadInfo** object. |
99| queryMimeType(): Promise\<string>                            | Queries the MIME type of this download task. This API uses a promise to return the MIME type. |
100| queryMimeType(callback: AsyncCallback\<string>): void        | Queries the MIME type of this download task. This API uses an asynchronous callback to return the MIME type. |
101
102**Table 3** DownloadConfig
103
104| Name          | Type    | Description                                        |
105| ------------- | ------- | -------------------------------------------------- |
106| url           | string  | Target URL.                                        |
107| header        | Object  | Request header.                                    |
108| enableMetered | boolean | Whether to allow downloads over a metered network. |
109| enableRoaming | boolean | Whether to allow downloads during network roaming. |
110| description   | string  | Description of the download task.                  |
111| networkType   | number  | Network type under which downloads are allowed.    |
112| filePath      | string  | File save path.                                    |
113| title         | string  | Title of the download task.                        |
114| background    | boolean | Download background.                               |
115
116**Table 4** DownloadInfo
117
118| Name               | Type   | Description                                   |
119| ------------------ | ------ | --------------------------------------------- |
120| description        | string | Description of the download task.             |
121| downloadedBytes    | number | Number of downloaded bytes.                   |
122| downloadId         | number | ID of the download task.                      |
123| failedReason       | number | Reason why the download task failed.          |
124| fileName           | string | Name of the file to save.                     |
125| filePath           | string | File save path.                               |
126| pausedReason       | number | Reason for suspending the download task.      |
127| status             | number | Status of the download task.                  |
128| targetURI          | string | URL of the download task.                     |
129| downloadTitle      | string | Title of the download task.                   |
130| downloadTotalBytes | number | Total number of bytes in the downloaded file. |
131
132**Table 5** Major APIs in UploadTask
133
134| API                                                          | Description                                                  |
135| ------------------------------------------------------------ | ------------------------------------------------------------ |
136| on(type: 'progress', callback:AsyncCallback <uploadedSize: number, totalSize: number> => void): void | Enables listening for upload task progress changes. This API uses an asynchronous callback to return the upload progress. If this API is called multiple times, the callback passed in the last call is used. |
137| on(type: 'headerReceive', callback: AsyncCallback\<object> => void): void | Enables listening for the header receive event. This API uses an asynchronous callback to return the HTTP header response. If this API is called multiple times, the callback passed in the last call is used. |
138| off(type: 'progress', callback:AsyncCallback<uploadedSize: number, totalSize: number>=> void): void | Disables listening for upload task progress changes. This API uses an asynchronous callback to return the upload progress. |
139| off(type: 'headerReceive', callback:AsyncCallback\<object> => void): void | Disables listening for the header receive event. This API uses an asynchronous callback to return the HTTP header response. |
140| remove(): Promise\<boolean>                                  | Removes this upload task. This API uses a promise to return the result. |
141| remove(callback: AsyncCallback\<boolean>): void              | Removes this upload task. This API uses an asynchronous callback to return the result. |
142| on(type: 'fail', callback: (err: number, result?: Array) => void): void | Enables listening for the upload failure event. This API uses a callback to return the result. |
143| off(type: 'fail', callback?: (err: number, result?: Array) => void): void | Disables listening for the upload failure event. This API uses a callback to return the result. |
144| on(type: 'complete', callback: (code: Array, result?: Array) => void): void | Enables listening for the upload completion event. This API uses a callback to return the result. |
145| off(type: 'complete', callback?: (code: Array, result?: Array) => void): void | Disables listening for the upload completion event. This API uses a callback to return the result. |
146
147**Table 6** UploadConfig
148
149| Name       | Type                | Description                   |
150| ---------- | ------------------- | ----------------------------- |
151| url        | string              | Target URL.                   |
152| header     | Object              | Request header.               |
153| header     | Object              | Request header.               |
154| files      | Array\<File>        | List of local files.          |
155| data       | Array\<RequestData> | List of upload request forms. |
156| background | boolean             | Upload background.            |
157
158**Table 7** File
159
160| Name     | Type   | Description                                                  |
161| -------- | ------ | ------------------------------------------------------------ |
162| filename | string | File name in the request header when multiple parts are submitted. |
163| name     | string | Name of a form item when multiple parts are submitted. The default value is **file**. |
164| uri      | string | Local path for storing files. Protocol types **dataability** and **internal** are supported. **internal** supports only temporary directories. Example: **dataability:///com.domainname.dataability.persondata/person/10/file.txt internal://cache/path/to/file.txt**. |
165| type     | string | Type of the file content. By default, the type is obtained based on the extension of the file name or URI. |
166
167**Table 8** RequestData
168
169| Name  | Type   | Description              |
170| ----- | ------ | ------------------------ |
171| name  | string | Name of a form element.  |
172| value | string | Value of a form element. |
173
174###  How to Use
175
176```js
177// Import the module.
178import request from '@ohos.request';
179```
180
181```js
182// Download service API usage description
183let downloadConfig = {
184  url: 'http://mirror.bjtu.edu.cn/kernel/linux/libs/libc5/libc5.cvs.tar.gz',
185  header: {},
186  enableMetered: true,
187  enableRoaming: true,
188  description: 'download libc from mirror site',
189  networkType: 1,
190  filePath: '/data/libc5.cvs.tgz',
191  title: 'download libc',
192}
193let downloadTask;
194
195```
196
1971. Obtain the **DownloadTask** instance.
198
199```js
200// Obtain the DownloadTask instance using a callback.
201request.download(downloadConfig, (err, data) => {
202    if (err) {
203        console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
204        return;
205    }
206    console.info('Success to request the download.);
207    downloadTask = data;
208});
209
210// Obtain the DownloadTask instance using a promise.
211request.download(downloadConfig).then((data) => {
212    console.info('Success to request the download.);
213    downloadTask = data;
214}).catch((err) => {
215    console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
216})
217// Obtain the DownloadTask instance using a callback.
218request.download(BaseContext, downloadConfig, (err, data) => {
219    if (err) {
220        console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
221        return;
222    }
223    console.info('Success to request the download.);
224    downloadTask = data;
225});
226
227// Obtain the DownloadTask instance using a promise.
228request.download(BaseContext, downloadConfig).then((data) => {
229    console.info('Success to request the download.);
230    downloadTask = data;
231}).catch((err) => {
232    console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
233})
234```
235
2362. Enable listening for download task progress changes.
237
238```js
239// Enable listening for download task progress changes and obtain the download progress using a callback.
240downloadTask.on('progress', (receivedSize, totalSize) => {
241    console.info("download receivedSize :" + receivedSize + " totalSize :" + totalSize);
242});
243```
244
2453. Enable listening for the complete event.
246
247```js
248// Enable listening for the complete event and obtain the result using a callback.
249downloadTask.on('complete', () => {
250    console.info("download task has been completed");
251});
252```
253
2544. Enable listening for the pause event.
255
256```js
257// Enable listening for the pause event and obtain the result using a callback.
258downloadTask.on('pause', () => {
259    console.info("download task has been paused");
260});
261```
262
2635. Enable listening for the remove event.
264
265```js
266// Enable listening for the remove event and obtain the result using a callback.
267downloadTask.on('remove', () => {
268    console.info("download task has been removed");
269});
270```
271
2726. Enable listening for the download failure event.
273
274```js
275// Enable listening for the download failure event and obtain the error code using a callback.
276downloadTask.on('fail', (error) => {
277    console.info("download fail error:" + error);
278});
279
280```
281
2827. Disable listening for download task progress changes.
283
284```js
285// Disable listening for download task progress changes and obtain the download progress using a callback.
286downloadTask.off('progress', (receivedSize, totalSize) => {
287    console.info("download receivedSize :" + receivedSize + " totalSize :" + totalSize);
288});
289
290```
291
2928. Disable listening for the complete event.
293
294```js
295// Disable listening for the complete event and obtain the result using a callback.
296downloadTask.off('complete', () => {
297    console.info("delete complete notification");
298});
299
300```
301
3029. Disable listening for the pause event.
303
304```js
305// Disable listening for the pause event and obtain the result using a callback.
306downloadTask.off('pause', () => {
307    console.info("delete pause notification");
308});
309
310```
311
31210. Disable listening for the pause event.
313
314```js
315// Disable listening for the remove event and obtain the result using a callback.
316downloadTask.off('remove', () => {
317    console.info("delete remove notification");
318});
319
320```
321
32211. Disable listening for the download failure event.
323
324```js
325// Disable listening for the download failure event and obtain the error code using a callback.
326downloadTask.off('fail', (error) => {
327    console.info("remove fail notification error:" + error);
328});
329
330```
331
33212. Remove the download task.
333
334```js
335// Remove the download task and obtain the result using a promise.
336downloadTask.remove().then((result) => {
337    if (result) {
338        console.info('Success to remove the download task.(promise) ');
339    } else {
340        console.error('Failed to remove the download task.(promise) ');
341    }
342}).catch((err) => {
343    console.error('Failed to remove the download task.(promise) Cause: ' + JSON.stringify(err));
344});
345
346// Remove the download task and obtain the result using a callback.
347downloadTask.remove((err, result) => {
348    if (err) {
349        console.error('Failed to remove the download task.(callback) Cause: ' + JSON.stringify(err));
350        return;
351    }
352    if (result) {
353        console.info('Success to remove the download task.(callback) ');
354    } else {
355        console.error('Failed to remove the download task.(callback) ');
356    }
357});
358
359```
360
36113. Pause the download task.
362
363```js
364// Pause the download task and obtain the result using a promise.
365downloadTask.pause().then(() => {
366	console.info('Success to pause the download task.(promise) ');
367}).catch((err) => {
368    console.error('Failed to pause the download task.(promise) Cause: ' + JSON.stringify(err));
369});
370
371// Pause the download task and obtain the result using a callback.
372downloadTask.pause((err) => {
373    if (err) {
374        console.error('Failed to pause the download task.(callback) Cause: ' + JSON.stringify(err));
375		return;
376    }
377	console.info('Success to pause the download task.(callback) ');
378});
379
380```
381
38214. Resume the download task.
383
384```js
385// Resume the download task and obtain the result using a promise.
386downloadTask.resume().then(() => {
387	console.info('Success to resume the download task.(promise) ');
388}).catch((err) => {
389    console.error('Failed to resume the download task.(promise) Cause: ' + JSON.stringify(err));
390});
391
392// Resume the download task and obtain the result using a callback.
393downloadTask.resume((err) => {
394    if (err) {
395        console.error('Failed to resume the download task.(callback) Cause: ' + JSON.stringify(err));
396		return;
397    }
398	console.info('Success to resume the download task.(callback) ');
399});
400
401```
402
40315. Query the download task.
404
405```js
406// Query the download task and obtain the result using a promise.
407downloadTask.query().then((downloadInfo) => {
408	console.info('Success to query the download task.(promise) ');
409}).catch((err) => {
410    console.error('Failed to query the download task.(promise) Cause: ' + JSON.stringify(err));
411});
412
413// Query the download task and obtain the result using a callback.
414downloadTask.query((err, downloadInfo) => {
415    if (err) {
416        console.error('Failed to query the download task.(callback) Cause: ' + JSON.stringify(err));
417		return;
418    }
419	console.info('Success to query the download task.(callback) ');
420});
421
422```
423
42416. Query the MIME type of the download task.
425
426```js
427// Query the MIME type of the download task and obtain the result using a promise.
428downloadTask.queryMimeType().then((mime) => {
429	console.info('Success to queryMimeType the download task.(promise) MimeType ' + JSON.stringify(mime));
430}).catch((err) => {
431    console.error('Failed to queryMimeType the download task.(promise) Cause: ' + JSON.stringify(err));
432});
433
434// Query the MIME type of the download task and obtain the result using a callback.
435downloadTask.queryMimeType((err, mime) => {
436    if (err) {
437        console.error('Failed to queryMimeType the download task.(callback) Cause: ' + JSON.stringify(err));
438		return;
439    }
440	console.info('Success to queryMimeType the download task.(promise) MimeType ' + JSON.stringify(mime));
441});
442
443```
444
445```js
446// Upload service API usage description
447
448```
449
4501. Upload files.
451
452```js
453// Upload a group of files.
454let url = 'http://192.168.2.211/files/';
455let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" };
456let file2 = { filename: "test", name: "test", uri: "internal://cache/test.zip", type: "zip" };
457let file3 = { filename: "test", name: "test", uri: "internal://cache/test.mp4", type: "mp4" };
458let file4 = { filename: "test", name: "test", uri: "internal://cache/test.exe", type: "exe" };
459let file5 = { filename: "test", name: "test", uri: "internal://cache/test.pdf", type: "pdf" };
460let file6 = { filename: "test", name: "test", uri: "internal://cache/test.txt", type: "txt" };
461let largeFile = { filename: "test", name: "test", uri: "internal://cache/testLarge.txt", type: "txt" };
462let dataabilityFile = { filename: "test", name: "test",
463  uri: "dataability://com.test.testApp/person/test.txt", type: "txt" };
464let files = [file1, file2, file3, file4, file5, file6, largeFile, dataabilityFile];
465let data = [{ name: "name123", value: "123" }];
466let uploadTask;
467
468```
469
4702. Obtain the **UploadTask** instance.
471
472```js
473// Obtain the UploadTask instance using a callback.
474request.upload({ url, header, "POST", files, data }, (err, data) => {
475    if (err) {
476        console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
477        return;
478    }
479    console.info('Success to request the upload.);
480    uploadTask = data;
481});
482
483// Obtain the UploadTask instance using a promise.
484request.upload({ url, header, "POST", files, data }).then((data) => {
485    console.info('Success to request the upload.);
486    uploadTask = data;
487}).catch((err) => {
488    console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
489})
490// Obtain the UploadTask instance using a callback.
491request.upload(BaseContext, { url, header, "POST", files, data }, (err, data) => {
492    if (err) {
493        console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
494        return;
495    }
496    console.info('Success to request the upload.);
497    uploadTask = data;
498});
499
500// Obtain the UploadTask instance using a promise.
501request.upload(BaseContext, { url, header, "POST", files, data }).then((data) => {
502    console.info('Success to request the upload.);
503    uploadTask = data;
504}).catch((err) => {
505    console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
506})
507
508```
509
5103. Enable listening for upload task progress changes.
511
512```js
513// Enable listening for upload task progress changes and obtain the result using a callback.
514uploadTask.on('progress', (uploadedSize, totalSize) => {
515    console.info("on progress upload uploadedSize :" + uploadedSize + " totalSize :" + totalSize);
516});
517
518```
519
5204. Enable listening for the header receive event.
521
522```js
523// Enable listening for the header receive event and obtain the result using a callback.
524uploadTask.on('headerReceive', (headers) => {
525    console.info("on headerReceive headers:" + JSON.stringify(headers));
526});
527
528```
529
5305. Enable listening for the upload completion event.
531
532```
533// Enable listening for the upload completion event and obtain the result using a callback.
534uploadTask.on('complete', (code,result) => {
535    console.info("upload task has been completed"+code);
536});
537
538```
539
5406. Enable listening for the upload failure event.
541
542```js
543// Enable listening for the upload failure event and obtain the result using a callback.
544uploadTask.on('fail', (error,result) => {
545    console.info("on fail error:" + error+"result is:"+result);
546});
547
548```
549
5507. Disable listening for upload task progress changes.
551
552```js
553// Disable listening for upload task progress changes and obtain the result using a callback.
554uploadTask.off('progress', (uploadedSize, totalSize) => {
555    console.info("on progress upload uploadedSize :" + uploadedSize + " totalSize :" + totalSize);
556});
557
558```
559
5608. Disable listening for the header receive event.
561
562```js
563// Disable listening for the header receive event and obtain the result using a callback.
564uploadTask.off('headerReceive', (headers) => {
565    console.info("on headerReceive headers:" + JSON.stringify(headers));
566});
567
568```
569
5709. Disable listening for the upload completion event.
571
572```js
573// Disable listening for the upload completion event and obtain the result using a callback.
574uploadTask.off('complete', (code,result) => {
575    console.info("delete complete notification");
576});
577
578```
579
58010. Disable listening for the upload failure event.
581
582```js
583// Disable listening for the upload failure event and obtain the result using a callback.
584uploadTask.off('fail', (error,result) => {
585    console.info("on fail error:" + error+"result is:"+result);
586});
587
588```
589
59011. Remove the upload task.
591
592```js
593// Remove the upload task and obtain the result using a promise.
594uploadTask.remove().then((result) => {
595    if (result) {
596        console.info('Success to remove the upload task.(promise) ');
597    } else {
598        console.error('Failed to remove the upload task.(promise) ');
599    }
600}).catch((err) => {
601    console.error('Failed to remove the upload task.(promise) Cause: ' + JSON.stringify(err));
602});
603
604// Remove the upload task and obtain the result using a callback.
605uploadTask.remove((err, result) => {
606    if (err) {
607        console.error('Failed to remove the upload task.(callback) Cause: ' + JSON.stringify(err));
608        return;
609    }
610    if (result) {
611        console.info('Success to remove the upload task.(callback) ');
612    } else {
613        console.error('Failed to remove the upload task.(callback) ');
614    }
615});
616
617```
618
619##  Repositories Involved
620
621[request_request](https://gitee.com/openharmony/request_request)