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