• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.net.http (Data Request)
2
3The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
4
5> **NOTE**
6>
7>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>
9
10## Modules to Import
11
12```ts
13import http from '@ohos.net.http';
14```
15
16## Example
17
18```ts
19// Import the http namespace.
20import http from '@ohos.net.http';
21import { BusinessError } from '@ohos.base';
22
23// Each httpRequest corresponds to an HTTP request task and cannot be reused.
24let httpRequest = http.createHttp();
25// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
26// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
27httpRequest.on('headersReceive', (header: Object) => {
28  console.info('header: ' + JSON.stringify(header));
29});
30
31class ExtraData {
32  public data: string;
33
34  constructor(data: string) {
35    this.data = data;
36  }
37}
38
39class Header {
40  public contentType: string;
41
42  constructor(contentType: string) {
43    this.contentType = contentType;
44  }
45}
46
47httpRequest.request( // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
48  "EXAMPLE_URL",
49  {
50    method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
51    // This parameter is used to transfer data when the POST request is used.
52    extraData: new ExtraData('data to send'),
53    expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data.
54    usingCache: true, // Optional. The default value is true.
55    priority: 1, // Optional. The default value is 1.
56    // You can add header fields based on service requirements.
57    header: new Header('application/json'),
58    readTimeout: 60000, // Optional. The default value is 60000, in ms.
59    connectTimeout: 60000 // Optional. The default value is 60000, in ms.
60    usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
61    usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API version 10.
62    caPath: '/path/to/cacert.pem', // Optional. The preset CA certificate is used by default. This field is supported since API version 10.
63    clientCert: { // Optional. The client certificate is not used by default. This field is supported since API version 11.
64      certPath: '/path/to/client.pem', // The client certificate is not used by default. This field is supported since API version 11.
65      keyPath: '/path/to/client.key', // If the certificate contains key information, an empty string is passed. This field is supported since API version 11.
66      certType: http.CertType.PEM, // Certificate type, optional. A certificate in the PEM format is used by default. This field is supported since API version 11.
67      keyPassword: "passwordToKey" // Password of the key file, optional. It is supported since API version 11.
68    },
69    multiFormDataList: [ // Optional. This field is valid only when content-Type in the header is multipart/form-data. It is supported since API version 11.
70      {
71        name: "Part1", // Data name. This field is supported since API version 11.
72        contentType: 'text/plain', // Data type. This field is supported since API version 11.
73        data: 'Example data', // Data content, optional. This field is supported since API version 11.
74        remoteFileName: 'example.txt' // Optional. This field is supported since API version 11.
75      }, {
76        name: "Part2", // Data name. This field is supported since API version 11.
77        contentType: 'text/plain', // Data type. This field is supported since API version 11.
78        // data/app/el2/100/base/com.example.myapplication/haps/entry/files/fileName.txt
79        filePath: `${getContext(this).filesDir}/fileName.txt`, // File path, optional. This field is supported since API version 11.
80        remoteFileName: 'fileName.txt' // Optional. This field is supported since API version 11.
81      }
82    ]
83  },
84  (err: BusinessError, data: http.HttpResponse) => {
85    if (!err) {
86      // data.result carries the HTTP response. Parse the response based on service requirements.
87      console.info('Result:' + JSON.stringify(data.result));
88      console.info('code:' + JSON.stringify(data.responseCode));
89      console.info('type:' + JSON.stringify(data.resultType));
90      // data.header carries the HTTP response header. Parse the content based on service requirements.
91      console.info('header:' + JSON.stringify(data.header));
92      console.info('cookies:' + JSON.stringify(data.cookies)); // Cookies are supported since API version 8.
93      // Unsubscribe from HTTP Response Header events.
94      httpRequest.off('headersReceive');
95      // Call destroy() to destroy the JavaScript object after the HTTP request is complete.
96      httpRequest.destroy();
97    } else {
98      console.info('error:' + JSON.stringify(err));
99      // Unsubscribe from HTTP Response Header events.
100      httpRequest.off('headersReceive');
101      // Call destroy() to destroy the JavaScript object after the HTTP request is complete.
102      httpRequest.destroy();
103    }
104  });
105```
106
107> **NOTE**
108> If the data in **console.info()** contains a newline character, the data will be truncated.
109
110## http.createHttp
111
112createHttp(): HttpRequest
113
114Creates an HTTP request. You can use this API to initiate or destroy an HTTP request, or enable or disable listening for HTTP Response Header events. An **HttpRequest** object corresponds to an HTTP request. To initiate multiple HTTP requests, you must create an **HttpRequest** object for each HTTP request.
115
116> **NOTE**
117> Call the **destroy()** method to release resources after the HttpRequest is complete.
118
119**System capability**: SystemCapability.Communication.NetStack
120
121**Return value**
122
123| Type       | Description                                                        |
124| :---------- | :----------------------------------------------------------- |
125| HttpRequest | An **HttpRequest** object, which contains the **request**, **requestInStream**, **destroy**, **on**, or **off** method.|
126
127**Example**
128
129```ts
130import http from '@ohos.net.http';
131
132let httpRequest = http.createHttp();
133```
134
135## HttpRequest
136
137Defines an HTTP request task. Before invoking methods of **HttpRequest**, you must call **createHttp()** to create an HTTP request task.
138
139### request
140
141request(url: string, callback: AsyncCallback\<HttpResponse\>): void
142
143Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result.
144
145> **NOTE**
146> This API supports only receiving of data not greater than 5 MB.
147
148**Required permissions**: ohos.permission.INTERNET
149
150**System capability**: SystemCapability.Communication.NetStack
151
152**Parameters**
153
154| Name  | Type                                          | Mandatory| Description                   |
155| -------- | ---------------------------------------------- | ---- | ---------------------- |
156| url      | string                                         | Yes  | URL for initiating an HTTP request.|
157| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes  | Callback used to return the result.   |
158
159**Error codes**
160
161| ID  | Error Message                                                 |
162|---------|-------------------------------------------------------|
163| 401     | Parameter error.                                      |
164| 201     | Permission denied.                                    |
165| 2300001 | Unsupported protocol.                                 |
166| 2300003 | URL using bad/illegal format or missing URL.          |
167| 2300005 | Couldn't resolve proxy name.                          |
168| 2300006 | Couldn't resolve host name.                           |
169| 2300007 | Couldn't connect to server.                           |
170| 2300008 | Weird server reply.                                   |
171| 2300009 | Access denied to remote resource.                     |
172| 2300016 | Error in the HTTP2 framing layer.                     |
173| 2300018 | Transferred a partial file.                           |
174| 2300023 | Failed writing received data to disk/application.     |
175| 2300025 | Upload failed.                                        |
176| 2300026 | Failed to open/read local data from file/application. |
177| 2300027 | Out of memory.                                        |
178| 2300028 | Timeout was reached.                                  |
179| 2300047 | Number of redirects hit maximum amount.               |
180| 2300052 | Server returned nothing (no headers, no data).        |
181| 2300055 | Failed sending data to the peer.                      |
182| 2300056 | Failure when receiving data from the peer.            |
183| 2300058 | Problem with the local SSL certificate.               |
184| 2300059 | Couldn't use specified SSL cipher.                    |
185| 2300060 | SSL peer certificate or SSH remote key was not OK.    |
186| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
187| 2300063 | Maximum file size exceeded.                           |
188| 2300070 | Disk full or allocation exceeded.                     |
189| 2300073 | Remote file already exists.                           |
190| 2300077 | Problem with the SSL CA cert (path? access rights?).  |
191| 2300078 | Remote file not found.                                |
192| 2300094 | An authentication function returned an error.         |
193| 2300999 | Unknown Other Error.                                  |
194
195> **NOTE**
196> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
197> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
198
199**Example**
200
201```ts
202import http from '@ohos.net.http';
203
204let httpRequest = http.createHttp();
205httpRequest.request("EXAMPLE_URL", (err: Error, data: http.HttpResponse) => {
206  if (!err) {
207    console.info('Result:' + data.result);
208    console.info('code:' + data.responseCode);
209    console.info('type:' + JSON.stringify(data.resultType));
210    console.info('header:' + JSON.stringify(data.header));
211    console.info('cookies:' + data.cookies); // Cookies are supported since API version 8.
212  } else {
213    console.info('error:' + JSON.stringify(err));
214  }
215});
216```
217
218### request
219
220request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpResponse\>):void
221
222Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result.
223
224> **NOTE**
225> This API supports only receiving of data not greater than 5 MB.
226
227**Required permissions**: ohos.permission.INTERNET
228
229**System capability**: SystemCapability.Communication.NetStack
230
231**Parameters**
232
233| Name  | Type                                          | Mandatory| Description                                           |
234| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
235| url      | string                                         | Yes  | URL for initiating an HTTP request.                        |
236| options  | HttpRequestOptions                             | Yes  | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
237| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes  | Callback used to return the result.                           |
238
239**Error codes**
240
241| ID  | Error Message                                                 |
242|---------|-------------------------------------------------------|
243| 401     | Parameter error.                                      |
244| 201     | Permission denied.                                    |
245| 2300001 | Unsupported protocol.                                 |
246| 2300003 | URL using bad/illegal format or missing URL.          |
247| 2300005 | Couldn't resolve proxy name.                          |
248| 2300006 | Couldn't resolve host name.                           |
249| 2300007 | Couldn't connect to server.                           |
250| 2300008 | Weird server reply.                                   |
251| 2300009 | Access denied to remote resource.                     |
252| 2300016 | Error in the HTTP2 framing layer.                     |
253| 2300018 | Transferred a partial file.                           |
254| 2300023 | Failed writing received data to disk/application.     |
255| 2300025 | Upload failed.                                        |
256| 2300026 | Failed to open/read local data from file/application. |
257| 2300027 | Out of memory.                                        |
258| 2300028 | Timeout was reached.                                  |
259| 2300047 | Number of redirects hit maximum amount.               |
260| 2300052 | Server returned nothing (no headers, no data).        |
261| 2300055 | Failed sending data to the peer.                      |
262| 2300056 | Failure when receiving data from the peer.            |
263| 2300058 | Problem with the local SSL certificate.               |
264| 2300059 | Couldn't use specified SSL cipher.                    |
265| 2300060 | SSL peer certificate or SSH remote key was not OK.    |
266| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
267| 2300063 | Maximum file size exceeded.                           |
268| 2300070 | Disk full or allocation exceeded.                     |
269| 2300073 | Remote file already exists.                           |
270| 2300077 | Problem with the SSL CA cert (path? access rights?).  |
271| 2300078 | Remote file not found.                                |
272| 2300094 | An authentication function returned an error.         |
273| 2300999 | Unknown Other Error.                                  |
274
275> **NOTE**
276> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
277> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
278
279**Example**
280
281```ts
282import http from '@ohos.net.http';
283
284class Header {
285  public contentType: string;
286
287  constructor(contentType: string) {
288    this.contentType = contentType;
289  }
290}
291
292let httpRequest = http.createHttp();
293let promise = httpRequest.request("EXAMPLE_URL", {
294  method: http.RequestMethod.GET,
295  connectTimeout: 60000,
296  readTimeout: 60000,
297  header: new Header('application/json')
298});
299
300promise.then((data:http.HttpResponse) => {
301  console.info('Result:' + data.result);
302  console.info('code:' + data.responseCode);
303  console.info('type:' + JSON.stringify(data.resultType));
304  console.info('header:' + JSON.stringify(data.header));
305  console.info('cookies:' + data.cookies); // Cookies are supported since API version 8.
306  console.info('header.content-Type:' + data.header);
307  console.info('header.Status-Line:' + data.header);
308
309}).catch((err:Error) => {
310  console.info('error:' + JSON.stringify(err));
311});
312```
313
314### request
315
316request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
317
318Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result.
319
320> **NOTE**
321> This API supports only receiving of data not greater than 5 MB.
322
323**Required permissions**: ohos.permission.INTERNET
324
325**System capability**: SystemCapability.Communication.NetStack
326
327**Parameters**
328
329| Name | Type              | Mandatory| Description                                           |
330| ------- | ------------------ | ---- | ----------------------------------------------- |
331| url     | string             | Yes  | URL for initiating an HTTP request.                        |
332| options | HttpRequestOptions | No  | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
333
334**Return value**
335
336| Type                                  | Description                             |
337| :------------------------------------- | :-------------------------------- |
338| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.|
339
340**Error codes**
341
342| ID  | Error Message                                                 |
343|---------|-------------------------------------------------------|
344| 401     | Parameter error.                                      |
345| 201     | Permission denied.                                    |
346| 2300001 | Unsupported protocol.                                 |
347| 2300003 | URL using bad/illegal format or missing URL.          |
348| 2300005 | Couldn't resolve proxy name.                          |
349| 2300006 | Couldn't resolve host name.                           |
350| 2300007 | Couldn't connect to server.                           |
351| 2300008 | Weird server reply.                                   |
352| 2300009 | Access denied to remote resource.                     |
353| 2300016 | Error in the HTTP2 framing layer.                     |
354| 2300018 | Transferred a partial file.                           |
355| 2300023 | Failed writing received data to disk/application.     |
356| 2300025 | Upload failed.                                        |
357| 2300026 | Failed to open/read local data from file/application. |
358| 2300027 | Out of memory.                                        |
359| 2300028 | Timeout was reached.                                  |
360| 2300047 | Number of redirects hit maximum amount.               |
361| 2300052 | Server returned nothing (no headers, no data).        |
362| 2300055 | Failed sending data to the peer.                      |
363| 2300056 | Failure when receiving data from the peer.            |
364| 2300058 | Problem with the local SSL certificate.               |
365| 2300059 | Couldn't use specified SSL cipher.                    |
366| 2300060 | SSL peer certificate or SSH remote key was not OK.    |
367| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
368| 2300063 | Maximum file size exceeded.                           |
369| 2300070 | Disk full or allocation exceeded.                     |
370| 2300073 | Remote file already exists.                           |
371| 2300077 | Problem with the SSL CA cert (path? access rights?).  |
372| 2300078 | Remote file not found.                                |
373| 2300094 | An authentication function returned an error.         |
374| 2300999 | Unknown Other Error.                                  |
375
376> **NOTE**
377> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
378> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
379
380**Example**
381
382```ts
383import http from '@ohos.net.http';
384
385class Header {
386  public contentType: string;
387
388  constructor(contentType: string) {
389    this.contentType = contentType;
390  }
391}
392
393let httpRequest = http.createHttp();
394let promise = httpRequest.request("EXAMPLE_URL", {
395  method: http.RequestMethod.GET,
396  connectTimeout: 60000,
397  readTimeout: 60000,
398  header: new Header('application/json')
399});
400promise.then((data:http.HttpResponse) => {
401  console.info('Result:' + data.result);
402  console.info('code:' + data.responseCode);
403  console.info('type:' + JSON.stringify(data.resultType));
404  console.info('header:' + JSON.stringify(data.header));
405  console.info('cookies:' + data.cookies); // Cookies are supported since API version 8.
406  console.info('header.content-Type:' + data.header);
407  console.info('header.Status-Line:' + data.header);
408}).catch((err:Error) => {
409  console.info('error:' + JSON.stringify(err));
410});
411```
412
413### destroy
414
415destroy(): void
416
417Destroys an HTTP request.
418
419**System capability**: SystemCapability.Communication.NetStack
420
421**Example**
422
423```ts
424import http from '@ohos.net.http';
425let httpRequest = http.createHttp();
426
427httpRequest.destroy();
428```
429
430### requestInStream<sup>10+</sup>
431
432requestInStream(url: string, callback: AsyncCallback\<number\>): void
433
434Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
435
436**Required permissions**: ohos.permission.INTERNET
437
438**System capability**: SystemCapability.Communication.NetStack
439
440**Parameters**
441
442| Name  | Type                                          | Mandatory| Description                                           |
443| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
444| url      | string                                         | Yes  | URL for initiating an HTTP request.                        |
445| callback | AsyncCallback\<number\>       | Yes  | Callback used to return the result.                                     |
446
447**Error codes**
448
449| ID  | Error Message                                                 |
450|---------|-------------------------------------------------------|
451| 401     | Parameter error.                                      |
452| 201     | Permission denied.                                    |
453| 2300001 | Unsupported protocol.                                 |
454| 2300003 | URL using bad/illegal format or missing URL.          |
455| 2300005 | Couldn't resolve proxy name.                          |
456| 2300006 | Couldn't resolve host name.                           |
457| 2300007 | Couldn't connect to server.                           |
458| 2300008 | Weird server reply.                                   |
459| 2300009 | Access denied to remote resource.                     |
460| 2300016 | Error in the HTTP2 framing layer.                     |
461| 2300018 | Transferred a partial file.                           |
462| 2300023 | Failed writing received data to disk/application.     |
463| 2300025 | Upload failed.                                        |
464| 2300026 | Failed to open/read local data from file/application. |
465| 2300027 | Out of memory.                                        |
466| 2300028 | Timeout was reached.                                  |
467| 2300047 | Number of redirects hit maximum amount.               |
468| 2300052 | Server returned nothing (no headers, no data).        |
469| 2300055 | Failed sending data to the peer.                      |
470| 2300056 | Failure when receiving data from the peer.            |
471| 2300058 | Problem with the local SSL certificate.               |
472| 2300059 | Couldn't use specified SSL cipher.                    |
473| 2300060 | SSL peer certificate or SSH remote key was not OK.    |
474| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
475| 2300063 | Maximum file size exceeded.                           |
476| 2300070 | Disk full or allocation exceeded.                     |
477| 2300073 | Remote file already exists.                           |
478| 2300077 | Problem with the SSL CA cert (path? access rights?).  |
479| 2300078 | Remote file not found.                                |
480| 2300094 | An authentication function returned an error.         |
481| 2300999 | Unknown Other Error.                                  |
482
483> **NOTE**
484> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
485> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
486
487**Example**
488
489```ts
490import http from '@ohos.net.http';
491import { BusinessError } from '@ohos.base';
492
493let httpRequest = http.createHttp();
494httpRequest.requestInStream("EXAMPLE_URL", (err: BusinessError, data: number) => {
495  if (!err) {
496    console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
497  } else {
498    console.info("requestInStream ERROR : err = " + JSON.stringify(err));
499  }
500})
501```
502
503### requestInStream<sup>10+</sup>
504
505requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void
506
507Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
508
509**Required permissions**: ohos.permission.INTERNET
510
511**System capability**: SystemCapability.Communication.NetStack
512
513**Parameters**
514
515| Name  | Type                                          | Mandatory| Description                                           |
516| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
517| url      | string                                         | Yes  | URL for initiating an HTTP request.                        |
518| options  | HttpRequestOptions                             | Yes  | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
519| callback | AsyncCallback\<[number](#responsecode)\>       | Yes  | Callback used to return the result.                                     |
520
521**Error codes**
522
523| ID  | Error Message                                                 |
524|---------|-------------------------------------------------------|
525| 401     | Parameter error.                                      |
526| 201     | Permission denied.                                    |
527| 2300001 | Unsupported protocol.                                 |
528| 2300003 | URL using bad/illegal format or missing URL.          |
529| 2300005 | Couldn't resolve proxy name.                          |
530| 2300006 | Couldn't resolve host name.                           |
531| 2300007 | Couldn't connect to server.                           |
532| 2300008 | Weird server reply.                                   |
533| 2300009 | Access denied to remote resource.                     |
534| 2300016 | Error in the HTTP2 framing layer.                     |
535| 2300018 | Transferred a partial file.                           |
536| 2300023 | Failed writing received data to disk/application.     |
537| 2300025 | Upload failed.                                        |
538| 2300026 | Failed to open/read local data from file/application. |
539| 2300027 | Out of memory.                                        |
540| 2300028 | Timeout was reached.                                  |
541| 2300047 | Number of redirects hit maximum amount.               |
542| 2300052 | Server returned nothing (no headers, no data).        |
543| 2300055 | Failed sending data to the peer.                      |
544| 2300056 | Failure when receiving data from the peer.            |
545| 2300058 | Problem with the local SSL certificate.               |
546| 2300059 | Couldn't use specified SSL cipher.                    |
547| 2300060 | SSL peer certificate or SSH remote key was not OK.    |
548| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
549| 2300063 | Maximum file size exceeded.                           |
550| 2300070 | Disk full or allocation exceeded.                     |
551| 2300073 | Remote file already exists.                           |
552| 2300077 | Problem with the SSL CA cert (path? access rights?).  |
553| 2300078 | Remote file not found.                                |
554| 2300094 | An authentication function returned an error.         |
555| 2300999 | Unknown Other Error.                                  |
556
557> **NOTE**
558> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
559> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
560
561**Example**
562
563```ts
564import http from '@ohos.net.http';
565import { BusinessError } from '@ohos.base';
566
567let httpRequest = http.createHttp();
568httpRequest.requestInStream("EXAMPLE_URL", (err: BusinessError<void> , data: number) => {
569  if (!err) {
570    console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
571  } else {
572    console.info("requestInStream ERROR : err = " + JSON.stringify(err));
573  }
574})
575```
576
577### requestInStream<sup>10+</sup>
578
579requestInStream(url: string, options? : HttpRequestOptions): Promise\<number\>
580
581Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response.
582
583**Required permissions**: ohos.permission.INTERNET
584
585**System capability**: SystemCapability.Communication.NetStack
586
587**Parameters**
588
589| Name | Type              | Mandatory| Description                                           |
590| ------- | ------------------ | ---- | ----------------------------------------------- |
591| url     | string             | Yes  | URL for initiating an HTTP request.                        |
592| options | HttpRequestOptions | No  | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
593
594**Return value**
595
596| Type                                  | Description                             |
597| :------------------------------------- | :-------------------------------- |
598| Promise\<[number](#responsecode)\> | Promise used to return the result.|
599
600**Error codes**
601
602| ID  | Error Message                                                 |
603|---------|-------------------------------------------------------|
604| 401     | Parameter error.                                      |
605| 201     | Permission denied.                                    |
606| 2300001 | Unsupported protocol.                                 |
607| 2300003 | URL using bad/illegal format or missing URL.          |
608| 2300005 | Couldn't resolve proxy name.                          |
609| 2300006 | Couldn't resolve host name.                           |
610| 2300007 | Couldn't connect to server.                           |
611| 2300008 | Weird server reply.                                   |
612| 2300009 | Access denied to remote resource.                     |
613| 2300016 | Error in the HTTP2 framing layer.                     |
614| 2300018 | Transferred a partial file.                           |
615| 2300023 | Failed writing received data to disk/application.     |
616| 2300025 | Upload failed.                                        |
617| 2300026 | Failed to open/read local data from file/application. |
618| 2300027 | Out of memory.                                        |
619| 2300028 | Timeout was reached.                                  |
620| 2300047 | Number of redirects hit maximum amount.               |
621| 2300052 | Server returned nothing (no headers, no data).        |
622| 2300055 | Failed sending data to the peer.                      |
623| 2300056 | Failure when receiving data from the peer.            |
624| 2300058 | Problem with the local SSL certificate.               |
625| 2300059 | Couldn't use specified SSL cipher.                    |
626| 2300060 | SSL peer certificate or SSH remote key was not OK.    |
627| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
628| 2300063 | Maximum file size exceeded.                           |
629| 2300070 | Disk full or allocation exceeded.                     |
630| 2300073 | Remote file already exists.                           |
631| 2300077 | Problem with the SSL CA cert (path? access rights?).  |
632| 2300078 | Remote file not found.                                |
633| 2300094 | An authentication function returned an error.         |
634| 2300999 | Unknown Other Error.                                  |
635
636> **NOTE**
637> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
638> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
639
640**Example**
641
642```ts
643import http from '@ohos.net.http';
644
645class Header {
646  public contentType: string;
647
648  constructor(contentType: string) {
649    this.contentType = contentType;
650  }
651}
652
653let httpRequest = http.createHttp();
654let promise = httpRequest.requestInStream("EXAMPLE_URL", {
655  method: http.RequestMethod.GET,
656  connectTimeout: 60000,
657  readTimeout: 60000,
658  header: new Header('application/json')
659});
660promise.then((data: number) => {
661  console.info("requestInStream OK!" + data);
662}).catch((err: Error) => {
663  console.info("requestInStream ERROR : err = " + JSON.stringify(err));
664});
665```
666
667### on("headerReceive")<sup>(deprecated)</sup>
668
669on(type: "headerReceive", callback: AsyncCallback\<Object\>): void
670
671Registers an observer for HTTP Response Header events.
672
673> **NOTE**
674> This API has been deprecated. You are advised to use [on("headersReceive")<sup>8+</sup>](#onheadersreceive8).
675
676**System capability**: SystemCapability.Communication.NetStack
677
678**Parameters**
679
680| Name  | Type                   | Mandatory| Description                             |
681| -------- | ----------------------- | ---- | --------------------------------- |
682| type     | string                  | Yes  | Event type. The value is **headerReceive**.|
683| callback | AsyncCallback\<Object\> | Yes  | Callback used to return the result.                       |
684
685**Example**
686
687```ts
688import http from '@ohos.net.http';
689import { BusinessError } from '@ohos.base';
690
691let httpRequest = http.createHttp();
692httpRequest.on("headerReceive", (data: BusinessError) => {
693  console.info("error:" + JSON.stringify(data));
694});
695```
696
697### off("headerReceive")<sup>(deprecated)</sup>
698
699off(type: "headerReceive", callback?: AsyncCallback\<Object\>): void
700
701Unregisters the observer for HTTP Response Header events.
702
703> **NOTE**
704>
705>1. This API has been deprecated. You are advised to use [off("headersReceive")<sup>8+</sup>](#offheadersreceive8).
706>
707>2. You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
708
709**System capability**: SystemCapability.Communication.NetStack
710
711**Parameters**
712
713| Name  | Type                   | Mandatory| Description                                 |
714| -------- | ----------------------- | ---- | ------------------------------------- |
715| type     | string                  | Yes  | Event type. The value is **headerReceive**.|
716| callback | AsyncCallback\<Object\> | No  | Callback used to return the result.                           |
717
718**Example**
719
720```ts
721import http from '@ohos.net.http';
722
723let httpRequest = http.createHttp();
724httpRequest.off("headerReceive");
725```
726
727### on("headersReceive")<sup>8+</sup>
728
729on(type: "headersReceive", callback: Callback\<Object\>): void
730
731Registers an observer for HTTP Response Header events.
732
733**System capability**: SystemCapability.Communication.NetStack
734
735**Parameters**
736
737| Name  | Type              | Mandatory| Description                              |
738| -------- | ------------------ | ---- | ---------------------------------- |
739| type     | string             | Yes  | Event type. The value is **headersReceive**.|
740| callback | Callback\<Object\> | Yes  | Callback used to return the result.                        |
741
742**Example**
743
744```ts
745import http from '@ohos.net.http';
746
747let httpRequest = http.createHttp();
748httpRequest.on("headersReceive", (header: Object) => {
749  console.info("header: " + JSON.stringify(header));
750});
751httpRequest.off("headersReceive");
752```
753
754### off("headersReceive")<sup>8+</sup>
755
756off(type: "headersReceive", callback?: Callback\<Object\>): void
757
758Unregisters the observer for HTTP Response Header events.
759
760> **NOTE**
761> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
762
763**System capability**: SystemCapability.Communication.NetStack
764
765**Parameters**
766
767| Name  | Type              | Mandatory| Description                                  |
768| -------- | ------------------ | ---- | -------------------------------------- |
769| type     | string             | Yes  | Event type. The value is **headersReceive**.|
770| callback | Callback\<Object\> | No  | Callback used to return the result.                            |
771
772**Example**
773
774```ts
775import http from '@ohos.net.http';
776
777let httpRequest = http.createHttp();
778httpRequest.on("headersReceive", (header: Object) => {
779  console.info("header: " + JSON.stringify(header));
780});
781httpRequest.off("headersReceive");
782```
783
784### once("headersReceive")<sup>8+</sup>
785
786once(type: "headersReceive", callback: Callback\<Object\>): void
787
788Registers a one-time observer for HTTP Response Header events. Once triggered, the observer will be removed. This API uses an asynchronous callback to return the result.
789
790**System capability**: SystemCapability.Communication.NetStack
791
792**Parameters**
793
794| Name  | Type              | Mandatory| Description                              |
795| -------- | ------------------ | ---- | ---------------------------------- |
796| type     | string             | Yes  | Event type. The value is **headersReceive**.|
797| callback | Callback\<Object\> | Yes  | Callback used to return the result.                        |
798
799**Example**
800
801```ts
802import http from '@ohos.net.http';
803
804let httpRequest = http.createHttp();
805httpRequest.once("headersReceive", (header: Object) => {
806  console.info("header: " + JSON.stringify(header));
807});
808```
809
810### on("dataReceive")<sup>10+</sup>
811
812on(type: "dataReceive", callback: Callback\<ArrayBuffer\>): void
813
814Registers an observer for events indicating receiving of HTTP streaming responses.
815
816> **NOTE**
817> Currently, listening for events related to HTTP streaming data upload is not supported.
818
819**System capability**: SystemCapability.Communication.NetStack
820
821**Parameters**
822
823| Name  | Type                   | Mandatory| Description                             |
824| -------- | ----------------------- | ---- | --------------------------------- |
825| type     | string                  | Yes  | Event type. The value is **dataReceive**.|
826| callback | AsyncCallback\<ArrayBuffer\> | Yes  | Callback used to return the result.                       |
827
828**Example**
829
830```ts
831import http from '@ohos.net.http';
832
833let httpRequest = http.createHttp();
834httpRequest.on("dataReceive", (data: ArrayBuffer) => {
835  console.info("dataReceive length: " + JSON.stringify(data.byteLength));
836});
837httpRequest.off("dataReceive");
838```
839
840### off("dataReceive")<sup>10+</sup>
841
842off(type: "dataReceive", callback?: Callback\<ArrayBuffer\>): void
843
844Unregisters the observer for events indicating receiving of HTTP streaming responses.
845
846> **NOTE**
847> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
848
849**System capability**: SystemCapability.Communication.NetStack
850
851**Parameters**
852
853| Name  | Type              | Mandatory| Description                                  |
854| -------- | ------------------ | ---- | -------------------------------------- |
855| type     | string             | Yes  | Event type. The value is **dataReceive**.|
856| callback | Callback\<ArrayBuffer\> | No  | Callback used to return the result.                            |
857
858**Example**
859
860```ts
861import http from '@ohos.net.http';
862
863let httpRequest = http.createHttp();
864httpRequest.on("dataReceive", (data: ArrayBuffer) => {
865  console.info("dataReceive length: " + JSON.stringify(data.byteLength));
866});
867httpRequest.off("dataReceive");
868```
869
870### on("dataEnd")<sup>10+</sup>
871
872on(type: "dataEnd", callback: Callback\<void\>): void
873
874Registers an observer for events indicating completion of receiving HTTP streaming responses.
875
876> **NOTE**
877> Currently, listening for events related to HTTP streaming data upload is not supported.
878
879**System capability**: SystemCapability.Communication.NetStack
880
881**Parameters**
882
883| Name  | Type                   | Mandatory| Description                             |
884| -------- | ----------------------- | ---- | --------------------------------- |
885| type     | string                  | Yes  | Event type. The value is **dataEnd**.|
886| callback | AsyncCallback\<void\>   | Yes  | Callback used to return the result.                       |
887
888**Example**
889
890```ts
891import http from '@ohos.net.http';
892
893let httpRequest = http.createHttp();
894httpRequest.on("dataEnd", () => {
895  console.info("Receive dataEnd !");
896});
897httpRequest.off("dataEnd");
898```
899
900### off("dataEnd")<sup>10+</sup>
901
902off(type: "dataEnd", callback?: Callback\<void\>): void
903
904Unregisters the observer for events indicating completion of receiving HTTP streaming responses.
905
906> **NOTE**
907> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
908
909**System capability**: SystemCapability.Communication.NetStack
910
911**Parameters**
912
913| Name  | Type              | Mandatory| Description                                  |
914| -------- | ------------------ | ---- | -------------------------------------- |
915| type     | string             | Yes  | Event type. The value is **dataEnd**.|
916| callback | Callback\<void\>   | No  | Callback used to return the result.                            |
917
918**Example**
919
920```ts
921import http from '@ohos.net.http';
922
923let httpRequest = http.createHttp();
924httpRequest.on("dataEnd", () => {
925  console.info("Receive dataEnd !");
926});
927httpRequest.off("dataEnd");
928```
929
930### on("dataReceiveProgress")<sup>10+</sup>
931
932on(type: "dataReceiveProgress", callback: Callback\<DataReceiveProgressInfo\>): void
933
934Registers an observer for events indicating progress of receiving HTTP streaming responses.
935
936> **NOTE**
937> Currently, listening for events related to HTTP streaming data upload is not supported.
938
939**System capability**: SystemCapability.Communication.NetStack
940
941**Parameters**
942
943| Name  | Type                   | Mandatory| Description                             |
944| -------- | ----------------------- | ---- | --------------------------------- |
945| type     | string                  | Yes  | Event type. The value is **dataReceiveProgress**.|
946| callback | AsyncCallback\<[DataReceiveProgressInfo](#datareceiveprogressinfo11)\>   | Yes  | Callback used to return the result.  |
947
948**Example**
949
950```ts
951import http from '@ohos.net.http';
952
953class RequestData {
954  receiveSize: number = 2000
955  totalSize: number = 2000
956}
957
958let httpRequest = http.createHttp();
959httpRequest.on("dataReceiveProgress", (data: RequestData) => {
960  console.info("dataReceiveProgress:" + JSON.stringify(data));
961});
962httpRequest.off("dataReceiveProgress");
963```
964
965### off("dataReceiveProgress")<sup>10+</sup>
966
967off(type: "dataReceiveProgress", callback?: Callback\<DataReceiveProgressInfo\>): void
968
969Unregisters the observer for events indicating progress of receiving HTTP streaming responses.
970
971> **NOTE**
972> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
973
974**System capability**: SystemCapability.Communication.NetStack
975
976**Parameters**
977
978| Name  | Type              | Mandatory| Description                                  |
979| -------- | ------------------ | ---- | -------------------------------------- |
980| type     | string             | Yes  | Event type. The value is **dataReceiveProgress**.|
981| callback | Callback\<[DataReceiveProgressInfo](#datareceiveprogressinfo11)\>   | No  | Callback used to return the result.     |
982
983**Example**
984
985```ts
986import http from '@ohos.net.http';
987
988class RequestData {
989  receiveSize: number = 2000
990  totalSize: number = 2000
991}
992
993let httpRequest = http.createHttp();
994httpRequest.on("dataReceiveProgress", (data: RequestData) => {
995  console.info("dataReceiveProgress:" + JSON.stringify(data));
996});
997httpRequest.off("dataReceiveProgress");
998```
999
1000### on("dataSendProgress")<sup>11+</sup>
1001
1002on(type: "dataSendProgress", callback: Callback\<DataSendProgressInfo\>): void
1003
1004Registers an observer for events indicating progress of sending HTTP requests.
1005
1006**System capability**: SystemCapability.Communication.NetStack
1007
1008**Parameters**
1009
1010| Name  | Type                   | Mandatory| Description                             |
1011| -------- | ----------------------- | ---- | --------------------------------- |
1012| type     | string                  | Yes  | Event type. The value is **dataSendProgress**.|
1013| callback | AsyncCallback\<[DataSendProgressInfo](#datasendprogressinfo11)\>   | Yes  | Callback used to return the result.  |
1014
1015**Example**
1016
1017```ts
1018import http from '@ohos.net.http';
1019
1020class SendData {
1021  sendSize: number = 2000
1022  totalSize: number = 2000
1023}
1024
1025let httpRequest = http.createHttp();
1026httpRequest.on("dataSendProgress", (data: SendData) => {
1027  console.info("dataSendProgress:" + JSON.stringify(data));
1028});
1029httpRequest.off("dataSendProgress");
1030```
1031
1032### off("dataSendProgress")<sup>11+</sup>
1033
1034off(type: "dataSendProgress", callback?: Callback\<DataSendProgressInfo\>): void
1035
1036Unregisters the observer for events indicating progress of sending HTTP requests.
1037
1038> **NOTE**
1039> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
1040
1041**System capability**: SystemCapability.Communication.NetStack
1042
1043**Parameters**
1044
1045| Name  | Type              | Mandatory| Description                                  |
1046| -------- | ------------------ | ---- | -------------------------------------- |
1047| type     | string             | Yes  | Event type. The value is **dataSendProgress**.|
1048| callback | Callback\<[DataSendProgressInfo](#datasendprogressinfo11)\>  | No| Callback used to return the result.  |
1049
1050**Example**
1051
1052```ts
1053import http from '@ohos.net.http';
1054
1055class SendData {
1056  sendSize: number = 2000
1057  totalSize: number = 2000
1058}
1059
1060let httpRequest = http.createHttp();
1061httpRequest.on("dataSendProgress", (data: SendData) => {
1062  console.info("dataSendProgress:" + JSON.stringify(data));
1063});
1064httpRequest.off("dataSendProgress");
1065```
1066
1067## HttpRequestOptions
1068
1069Specifies the type and value range of the optional parameters in the HTTP request.
1070
1071**System capability**: SystemCapability.Communication.NetStack
1072
1073| Name        | Type                                         | Mandatory| Description                                                        |
1074| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
1075| method         | [RequestMethod](#requestmethod)               | No  | Request method. The default value is **GET**.                                                  |
1076| extraData      | string \| Object \| ArrayBuffer | No  | Additional data for sending a request. This parameter is not used by default.<br>- If the HTTP request uses a POST or PUT method, this field serves as the content of the HTTP request and is encoded in UTF-8 format. If **content-Type** is **application/x-www-form-urlencoded**, the data in the request body must be encoded in the format of **key1=value1&key2=value2&key3=value3** after URL transcoding and this field is usually in the String format. If **content-Type** is **text/xml**, this field is usually in the String format. If **content-Type** is **application/json**, this field is usually in the Object format. If **content-Type** is **application/octet-stream**, this field is usually in the ArrayBuffer format. If **content-Type** is **multipart/form-data** and the content to be uploaded is a file, this field is usually in the ArrayBuffer format. The preceding information is for reference only and may vary according to the actual situation.<br>- If the HTTP request uses the GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter serves as a supplement to HTTP request parameters. Parameters of the string type need to be encoded before being passed to the HTTP request. Parameters of the object type do not need to be precoded and will be directly concatenated to the URL. Parameters of the ArrayBuffer type will not be concatenated to the URL.|
1077| expectDataType<sup>9+</sup>  | [HttpDataType](#httpdatatype9)  | No  | Type of the returned data. This parameter is not used by default. If this parameter is set, the system returns the specified type of data preferentially.|
1078| usingCache<sup>9+</sup>      | boolean                         | No  | Whether to use the cache. The default value is **true**.  |
1079| priority<sup>9+</sup>        | number                          | No  | Priority. The value range is [1,1000]. The default value is **1**.                          |
1080| header                       | Object                          | No  | HTTP request header. The default value is **{'content-Type': 'application/json'}**.  |
1081| readTimeout                  | number                          | No  | Read timeout duration. The default value is **60000**, in ms.<br>The value **0** indicates no timeout.|
1082| connectTimeout               | number                          | No  | Connection timeout interval. The default value is **60000**, in ms.             |
1083| usingProtocol<sup>9+</sup>   | [HttpProtocol](#httpprotocol9)  | No  | Protocol. The default value is automatically specified by the system.                            |
1084| usingProxy<sup>10+</sup>     | boolean \| HttpProxy               | No  | Whether to use HTTP proxy. The default value is **false**, which means not to use HTTP proxy.<br>- If **usingProxy** is of the **Boolean** type and the value is **true**, network proxy is used by default.<br>- If **usingProxy** is of the **HttpProxy** type, the specified network proxy is used.|
1085| caPath<sup>10+</sup>     | string               | No  | Path of CA certificates. If a path is set, the system uses the CA certificates in this path. If a path is not set, the system uses the preset CA certificate, namely, **/etc/ssl/certs/cacert.pem**. This path is the sandbox mapping path, which can be obtained through **Global.getContext().filesDir**. Currently, only **.pem** certificates are supported.                            |
1086| resumeFrom<sup>11+</sup> | number | No| Start position for file upload or download. According to section 3.1 of RFC 7233:<br>- If this field is set when the PUT method is used, unknown problems may occur.<br>- The value ranges from **1** to **4294967296** (4 GB). If the value is out of this range, this field does not take effect.|
1087| resumeTo<sup>11+</sup> | number | No| End position for file upload or download. According to section 3.1 of RFC 7233:<br>- If this field is set when the PUT method is used, unknown problems may occur.<br>- The value ranges from **1** to **4294967296** (4 GB). If the value is out of this range, this field does not take effect.|
1088| clientCert<sup>11+</sup> | [ClientCert](#clientcert11) | No| Client certificate.|
1089| dnsOverHttps<sup>11+</sup> | string | No| DNS resolution for a server that uses the HTTPS protocol.<br>The value must be URL-encoded in the following format: "https://host:port/path".|
1090| dnsServers<sup>11+</sup> | Array<string> | No| Array of DNS servers used for DNS resolution.<br>- You can set a maximum of three DNS servers. If there are more than three DNS servers, only the first three DNS servers are used.<br>- The DNS servers must be expressed as IPv4 or IPv6 addresses.|
1091| maxLimit<sup>11+</sup>   | number   | No| Maximum number of bytes in a response. The default value is **5*1024*1024**. The maximum value is **100*1024*1024**. |
1092| multiFormDataList<sup>11+</sup> | Array<[MultiFormData](#multiformdata11)> | No| Form data list. This field is valid when **content-Type** is set to **multipart/form-data**.|
1093
1094## RequestMethod
1095
1096Defines an HTTP request method.
1097
1098**System capability**: SystemCapability.Communication.NetStack
1099
1100| Name   | Value     | Description               |
1101| :------ | ------- | :------------------ |
1102| OPTIONS | "OPTIONS" | OPTIONS method.|
1103| GET     | "GET"     | GET method.    |
1104| HEAD    | "HEAD"    | HEAD method.   |
1105| POST    | "POST"    | POST method.   |
1106| PUT     | "PUT"     | PUT method.    |
1107| DELETE  | "DELETE"  | DELETE method. |
1108| TRACE   | "TRACE"   | TRACE method.  |
1109| CONNECT | "CONNECT" | CONNECT method.|
1110
1111## ResponseCode
1112
1113Enumerates the response codes for an HTTP request.
1114
1115**System capability**: SystemCapability.Communication.NetStack
1116
1117| Name             | Value  | Description                                                        |
1118| ----------------- | ---- | ------------------------------------------------------------ |
1119| OK                | 200  | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests.                           |
1120| CREATED           | 201  | "Created." The request has been successfully sent and a new resource is created.                          |
1121| ACCEPTED          | 202  | "Accepted." The request has been accepted, but the processing has not been completed.                        |
1122| NOT_AUTHORITATIVE | 203  | "Non-Authoritative Information." The request is successful.                                      |
1123| NO_CONTENT        | 204  | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body.                      |
1124| RESET             | 205  | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content.                                                  |
1125| PARTIAL           | 206  | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource.                     |
1126| MULT_CHOICE       | 300  | "Multiple Choices." The requested resource corresponds to any one of a set of representations.                                                  |
1127| MOVED_PERM        | 301  | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.|
1128| MOVED_TEMP        | 302  | "Moved Temporarily." The requested resource is moved temporarily to a different URI.                                                  |
1129| SEE_OTHER         | 303  | "See Other." The response to the request can be found under a different URI.                                              |
1130| NOT_MODIFIED      | 304  | "Not Modified." The client has performed a conditional GET request and access is allowed, but the content has not been modified.                                                    |
1131| USE_PROXY         | 305  | "Use Proxy." The requested resource can only be accessed through the proxy.                                                  |
1132| BAD_REQUEST       | 400  | "Bad Request." The request could not be understood by the server due to incorrect syntax.                       |
1133| UNAUTHORIZED      | 401  | "Unauthorized." The request requires user authentication.                                    |
1134| PAYMENT_REQUIRED  | 402  | "Payment Required." This code is reserved for future use.                                            |
1135| FORBIDDEN         | 403  | "Forbidden." The server understands the request but refuses to process it.            |
1136| NOT_FOUND         | 404  | "Not Found." The server does not find anything matching the Request-URI.                |
1137| BAD_METHOD        | 405  | "Method Not Allowed." The method specified in the request is not allowed for the resource identified by the Request-URI.                                  |
1138| NOT_ACCEPTABLE    | 406  | "Not Acceptable." The server cannot fulfill the request according to the content characteristics of the request.                 |
1139| PROXY_AUTH        | 407  | "Proxy Authentication Required." The request requires user authentication with the proxy.                                    |
1140| CLIENT_TIMEOUT    | 408  | "Request Timeout." The client fails to generate a request within the timeout period.                                        |
1141| CONFLICT          | 409  | "Conflict." The request cannot be fulfilled due to a conflict with the current state of the resource. Conflicts are most likely to occur in response to a PUT request. |
1142| GONE              | 410  | "Gone." The requested resource has been deleted permanently and is no longer available.                                 |
1143| LENGTH_REQUIRED   | 411  | "Length Required." The server refuses to process the request without a defined Content-Length.    |
1144| PRECON_FAILED     | 412  | "Precondition Failed." The precondition in the request is incorrect.                              |
1145| ENTITY_TOO_LARGE  | 413  | "Request Entity Too Large." The server refuses to process a request because the request entity is larger than the server is able to process.           |
1146| REQ_TOO_LONG      | 414  | "Request-URI Too Long." The Request-URI is too long for the server to process.             |
1147| UNSUPPORTED_TYPE  | 415  | "Unsupported Media Type." The server is unable to process the media format in the request.                                   |
1148| RANGE_NOT_SATISFIABLE | 416  | "Range Not Satisfiable." The server cannot serve the requested ranges.                                 |
1149| INTERNAL_ERROR    | 500  | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request.                              |
1150| NOT_IMPLEMENTED   | 501  | "Not Implemented." The server does not support the function required to fulfill the request.                      |
1151| BAD_GATEWAY       | 502  | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.|
1152| UNAVAILABLE       | 503  | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance.      |
1153| GATEWAY_TIMEOUT   | 504  | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period.        |
1154| VERSION           | 505  | "HTTP Version Not Supported." The server does not support the HTTP protocol version used in the request.                                 |
1155
1156## HttpResponse
1157
1158Defines the response to an HTTP request.
1159
1160**System capability**: SystemCapability.Communication.NetStack
1161
1162| Name                | Type                                        | Mandatory| Description                                                         |
1163| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
1164| result               | string \| Object<sup>deprecated 8+</sup> \| ArrayBuffer<sup>8+</sup> | Yes  | Response content returned based on **Content-type** in the response header. If **HttpRequestOptions** does not contain the **expectDataType** field, the response content is returned according to the following rules:<br>- application/json: string in JSON format<br>- application/octet-stream: ArrayBuffer<br>- image: ArrayBuffer<br>- Others: string<br> If **HttpRequestOptions** contains the **expectDataType** field, the response content must be of the same type as the data returned by the server.|
1165| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9)             | Yes  | Type of the return value.                          |
1166| responseCode         | [ResponseCode](#responsecode) \| number      | Yes  | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**.|
1167| header               | Object                                       | Yes  | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- content-type: header['content-type'];<br>- status-line: header['status-line'];<br>- date: header.date/header['date'];<br>- server: header.server/header['server'];|
1168| cookies<sup>8+</sup> | string                                       | Yes  | Cookies returned by the server.                                      |
1169| performanceTiming<sup>11+</sup> | [PerformanceTiming](#performancetiming11) | Yes| Time consumed in each phase of an HTTP request.|
1170
1171## ClientCert<sup>11+</sup>
1172
1173Defines the client certificate type.
1174
1175**System capability**: SystemCapability.Communication.NetStack
1176
1177| Name| Type| Mandatory| Description|
1178| -------- | -------| --- | ----------- |
1179| certPath | string | Yes| Certificate path.|
1180| certType | [CertType](#certtype11) | No| Certificate type. The default value is **PEM**.|
1181| keyPath | string | Yes| Path of the certificate key file.|
1182| keyPassword | string | No | Password of the certificate key file.|
1183
1184## PerformanceTiming<sup>11+</sup>
1185
1186Configures the timing for performance tracing, in ms.
1187
1188**System capability**: SystemCapability.Communication.NetStack
1189
1190| Name      | Type  | Mandatory  | Description                  |
1191| ---------- | ------ | ---- | --------------------- |
1192| dnsTiming  | number | Yes  | Duration from the time when the [request](#request) is sent to the time when the DNS resolution is complete.|
1193| tcpTiming  | number | Yes  | Duration from the time when the [request](#request) is sent to the time when the TCP connection is complete.|
1194| tlsTiming  | number | Yes  | Duration from the time when the [request](#request) is sent to the time when the TLS connection is complete.|
1195| firstSendTiming  | number | Yes  | Duration from the time when the [request](#request) is sent to the time when the first byte is sent.|
1196| firstReceiveTiming  | number | Yes  | Duration from the time when the [request](#request) is sent to the time when the first byte is received.|
1197| totalFinishTiming  | number | Yes  | Duration from the time when the [request](#request) is sent to the time when the request is complete.|
1198| redirectTiming  | number | Yes  | Duration from the time when the [request](#request) is sent to the time when all redirection steps are complete.|
1199| responseHeaderTiming  | number | Yes  | Duration from the time when the [request](#request) is sent to the time when the header resolution is complete.|
1200| responseBodyTiming  | number | Yes  | Duration from the time when the [request](#request) is sent to the time when the body resolution is complete.|
1201| totalTiming  | number | Yes  | Duration from the time when the [request](#request) is sent to the time when a callback is returned to the application.|
1202
1203## DataReceiveProgressInfo<sup>11+</sup>
1204
1205Defines the data receiving progress information.
1206
1207**System capability**: SystemCapability.Communication.NetStack
1208
1209| Name| Type| Mandatory| Description|
1210| ---- | ---- | ---- | ---- |
1211|  receiveSize        | number | Yes | Size of data that has been received, in bytes.          |
1212| totalSize| number | Yes| Total size of data to be received, in bytes.|
1213
1214## DataSendProgressInfo<sup>11+</sup>
1215
1216Defines the data sending progress information.
1217
1218**System capability**: SystemCapability.Communication.NetStack
1219
1220### Attributes
1221
1222| Name| Type| Mandatory| Description|
1223| ---- | ---- | ---- | ---- |
1224| sendSize        | number | Yes | Size of data to be sent, in bytes. |
1225| totalSize | number | Yes| Total size of data to be sent, in bytes.|
1226
1227## MultiFormData<sup>11+</sup>
1228
1229Defines the type of multi-form data.
1230
1231**System capability**: SystemCapability.Communication.NetStack
1232
1233| Name| Type| Mandatory| Description|
1234| ---- | ---- | ---- | ---- |
1235| name        | string | Yes | Data name.                                                                     |
1236| contentType | string | Yes| Data type, for example, **text/plain**, **image/png**, **image/jpeg**, **audio/mpeg**, or **video/mp4**.|
1237| remoteFileName | string | No| Name of the file uploaded to the server.                                                |
1238| data | string \| Object \| ArrayBuffer | No| Form data content.                                                |
1239| filePath | string | No| File path. This field is used to configure the MIME body content based on the file content. This field is used as the substitute of **data** to set the file data as data content. If **data** is empty, **filePath** must be set. If **data** is present, **filePath** does not take effect.|
1240
1241## http.createHttpResponseCache<sup>9+</sup>
1242
1243createHttpResponseCache(cacheSize?: number): HttpResponseCache
1244
1245Creates a default object to store responses to HTTP access requests.
1246
1247**System capability**: SystemCapability.Communication.NetStack
1248
1249**Parameters**
1250
1251| Name  | Type                                   | Mandatory| Description      |
1252| -------- | --------------------------------------- | ---- | ---------- |
1253| cacheSize | number | No| Cache size. The maximum value is 10\*1024\*1024 (10 MB). By default, the maximum value is used.|
1254
1255**Return value**
1256
1257| Type       | Description                                                        |
1258| :---------- | :----------------------------------------------------------- |
1259| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.|
1260
1261**Example**
1262
1263```ts
1264import http from '@ohos.net.http';
1265
1266let httpResponseCache = http.createHttpResponseCache();
1267```
1268
1269## HttpResponseCache<sup>9+</sup>
1270
1271Defines an object that stores the response to an HTTP request. Before invoking APIs provided by **HttpResponseCache**, you must call [createHttpResponseCache()](#httpcreatehttpresponsecache9) to create an **HttpRequestTask** object.
1272
1273### flush<sup>9+</sup>
1274
1275flush(callback: AsyncCallback\<void\>): void
1276
1277Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses an asynchronous callback to return the result. Cached data includes the response header (header), response body (result), cookies, request time (requestTime), and response time (responseTime).
1278
1279**System capability**: SystemCapability.Communication.NetStack
1280
1281**Parameters**
1282
1283| Name  | Type                                   | Mandatory| Description      |
1284| -------- | --------------------------------------- | ---- | ---------- |
1285| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
1286
1287**Example**
1288
1289```ts
1290import http from '@ohos.net.http';
1291import { BusinessError } from '@ohos.base';
1292
1293let httpResponseCache = http.createHttpResponseCache();
1294httpResponseCache.flush((err: BusinessError) => {
1295  if (err) {
1296    console.info('flush fail');
1297    return;
1298  }
1299  console.info('flush success');
1300});
1301```
1302
1303### flush<sup>9+</sup>
1304
1305flush(): Promise\<void\>
1306
1307Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses a promise to return the result.
1308
1309**System capability**: SystemCapability.Communication.NetStack
1310
1311**Return value**
1312
1313| Type                             | Description                                 |
1314| --------------------------------- | ------------------------------------- |
1315| Promise\<void\> | Promise used to return the result.|
1316
1317**Example**
1318
1319```ts
1320import http from '@ohos.net.http';
1321import { BusinessError } from '@ohos.base';
1322
1323let httpResponseCache = http.createHttpResponseCache();
1324httpResponseCache.flush().then(() => {
1325  console.info('flush success');
1326}).catch((err: BusinessError) => {
1327  console.info('flush fail');
1328});
1329```
1330
1331### delete<sup>9+</sup>
1332
1333delete(callback: AsyncCallback\<void\>): void
1334
1335Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result.
1336
1337**System capability**: SystemCapability.Communication.NetStack
1338
1339**Parameters**
1340
1341| Name  | Type                                   | Mandatory| Description      |
1342| -------- | --------------------------------------- | ---- | ---------- |
1343| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
1344
1345**Example**
1346
1347```ts
1348import http from '@ohos.net.http';
1349import { BusinessError } from '@ohos.base';
1350
1351let httpResponseCache = http.createHttpResponseCache();
1352httpResponseCache.delete((err: BusinessError) => {
1353  if (err) {
1354    console.info('delete fail');
1355    return;
1356  }
1357  console.info('delete success');
1358});
1359```
1360
1361### delete<sup>9+</sup>
1362
1363delete(): Promise\<void\>
1364
1365Disables the cache and deletes the data in it. This API uses a promise to return the result.
1366
1367**System capability**: SystemCapability.Communication.NetStack
1368
1369**Return value**
1370
1371| Type                             | Description                                 |
1372| --------------------------------- | ------------------------------------- |
1373| Promise\<void\> | Promise used to return the result.|
1374
1375**Example**
1376
1377```ts
1378import http from '@ohos.net.http';
1379import { BusinessError } from '@ohos.base';
1380
1381let httpResponseCache = http.createHttpResponseCache();
1382httpResponseCache.delete().then(() => {
1383  console.info('delete success');
1384}).catch((err: Error) => {
1385  console.info('delete fail');
1386});
1387```
1388
1389## HttpDataType<sup>9+</sup>
1390
1391Enumerates HTTP data types.
1392
1393**System capability**: SystemCapability.Communication.NetStack
1394
1395| Name| Value| Description    |
1396| ------------------  | -- | ----------- |
1397| STRING              | 0 | String type.|
1398| OBJECT              | 1 | Object type.   |
1399| ARRAY_BUFFER        | 2 | Binary array type.|
1400
1401## HttpProtocol<sup>9+</sup>
1402
1403Enumerates HTTP protocol versions.
1404
1405**System capability**: SystemCapability.Communication.NetStack
1406
1407| Name | Description    |
1408| :-------- | :----------- |
1409| HTTP1_1   |  HTTP1.1 |
1410| HTTP2     |  HTTP2   |
1411| HTTP3<sup>11+</sup> | HTTP3 protocol. If the system or server does not support HTTP3, the HTTP protocol of an earlier version is used.<br>This field is valid only for HTTPS URLs. For HTTP URLs, the request fails.|
1412
1413## CertType<sup>11+</sup>
1414
1415Enumerates certificate types.
1416
1417**System capability**: SystemCapability.Communication.NetStack
1418
1419| Name| Description      |
1420| --- | ---------- |
1421| PEM | PEM certificate.|
1422| DER | DER certificate.|
1423| P12 | P12 certificate.|
1424
1425<!--no_check-->