1# @ohos.net.http (Data Request) 2 3The **http** module provides APIs for implementing HTTP data request capabilities. 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## Modules to Import 9 10```ts 11import { http } from '@kit.NetworkKit'; 12``` 13 14## Example 15 16```ts 17// Import the http namespace. 18import { http } from '@kit.NetworkKit'; 19import { BusinessError } from '@kit.BasicServicesKit'; 20 21// Each httpRequest corresponds to an HTTP request task and cannot be reused. 22let httpRequest = http.createHttp(); 23// This API is used to listen for HTTP Response Header events, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP response header events. 24// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. 25httpRequest.on('headersReceive', (header: Object) => { 26 console.info('header: ' + JSON.stringify(header)); 27}); 28 29httpRequest.request(// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. 30 "EXAMPLE_URL", 31 { 32 method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. 33 // This field is used to transfer the request body when a POST request is used. Its format needs to be negotiated with the server. 34 extraData: 'data to send', 35 expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data. 36 usingCache: true, // Optional. The default value is true. 37 priority: 1, // Optional. The default value is 1. 38 // You can add header fields based on service requirements. 39 header: { 'Accept' : 'application/json' }, 40 readTimeout: 60000, // Optional. The default value is 60000, in ms. 41 connectTimeout: 60000 // Optional. The default value is 60000, in ms. 42 usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. 43 usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API version 10. 44 caPath: '/path/to/cacert.pem', // Optional. The preset CA certificate is used by default. This field is supported since API version 10. 45 clientCert: { // Optional. The client certificate is not used by default. This field is supported since API version 11. 46 certPath: '/path/to/client.pem', // The client certificate is not used by default. This field is supported since API version 11. 47 keyPath: '/path/to/client.key', // If the certificate contains key information, an empty string is passed. This field is supported since API version 11. 48 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. 49 keyPassword: "passwordToKey" // Password of the key file, optional. It is supported since API version 11. 50 }, 51 certificatePinning: [ // Optional. It determines whether to enable dynamic configuration of certificate pinning. This attribute is supported since API version 12. 52 { 53 publicKeyHash: 'Pin1', // Certificate PIN passed by the application. This attribute is supported since API version 12. 54 hashAlgorithm: 'SHA-256' // Encryption algorithm. Currently, it can only be set to SHA-256. This attribute is supported since API version 12. 55 }, { 56 publicKeyHash: 'Pin2', // Certificate PIN passed by the application. This attribute is supported since API version 12. 57 hashAlgorithm: 'SHA-256' // Encryption algorithm. Currently, it can only be set to SHA-256. This attribute is supported since API version 12. 58 } 59 ], 60 multiFormDataList: [ // Optional. This field is valid only when content-Type in the header is multipart/form-data. It is supported since API version 11. 61 { 62 name: "Part1", // Data name. This field is supported since API version 11. 63 contentType: 'text/plain', // Data type. This field is supported since API version 11. 64 data: 'Example data', // Data content, optional. This field is supported since API version 11. 65 remoteFileName: 'example.txt' // Optional. This field is supported since API version 11. 66 }, { 67 name: "Part2", // Data name. This field is supported since API version 11. 68 contentType: 'text/plain', // Data type. This field is supported since API version 11. 69 // data/app/el2/100/base/com.example.myapplication/haps/entry/files/fileName.txt 70 filePath: `${getContext(this).filesDir}/fileName.txt`, // File path, optional. This field is supported since API version 11. 71 remoteFileName: 'fileName.txt' // Optional. This field is supported since API version 11. 72 } 73 ] 74 addressFamily: http.AddressFamily.DEFAULT // Optional. By default, the IPv4 or IPv6 address of the target domain name is selected. This attribute is supported since API version 15. 75 }, 76 (err: BusinessError, data: http.HttpResponse) => { 77 if (!err) { 78 // data.result carries the HTTP response. Parse the response based on service requirements. 79 console.info('Result:' + JSON.stringify(data.result)); 80 console.info('code:' + JSON.stringify(data.responseCode)); 81 console.info('type:' + JSON.stringify(data.resultType)); 82 // data.header carries the HTTP response header. Parse the content based on service requirements. 83 console.info('header:' + JSON.stringify(data.header)); 84 console.info('cookies:' + JSON.stringify(data.cookies)); // Cookies are supported since API version 8. 85 // Unsubscribe from HTTP Response Header events. 86 httpRequest.off('headersReceive'); 87 // Call destroy() to destroy the JavaScript object after the HTTP request is complete. 88 httpRequest.destroy(); 89 } else { 90 console.info('error:' + JSON.stringify(err)); 91 // Unsubscribe from HTTP Response Header events. 92 httpRequest.off('headersReceive'); 93 // Call destroy() to destroy the JavaScript object after the HTTP request is complete. 94 httpRequest.destroy(); 95 } 96 }); 97``` 98 99> **NOTE** 100> If the data in **console.info()** contains a newline character, the data will be truncated. 101> 102> HTTP responses compressed by the brotli algorithm are supported since API version 12. 103 104## http.createHttp 105 106createHttp(): HttpRequest 107 108Creates 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. 109 110> **NOTE** 111> Call the **destroy()** method to release resources after the HttpRequest is complete. 112 113**Atomic service API**: This API can be used in atomic services since API version 11. 114 115**System capability**: SystemCapability.Communication.NetStack 116 117**Return value** 118 119| Type | Description | 120| :---------- | :----------------------------------------------------------- | 121| HttpRequest | An **HttpRequest** object, which contains the **request**, **requestInStream**, **destroy**, **on**, or **off** method.| 122 123**Example** 124 125```ts 126import { http } from '@kit.NetworkKit'; 127 128let httpRequest = http.createHttp(); 129``` 130 131## HttpRequest 132 133Defines an HTTP request task. Before invoking methods of **HttpRequest**, you must call **createHttp()** to create an HTTP request task. 134 135### request 136 137request(url: string, callback: AsyncCallback\<HttpResponse\>): void 138 139Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. 140 141> **NOTE** 142> This API supports only receiving of data not greater than 5 MB. 143> If the URL contains non-English characters, call **encodeURL(url)** to encode the URL before initiating an HTTP request. 144 145**Required permissions**: ohos.permission.INTERNET 146 147**Atomic service API**: This API can be used in atomic services since API version 11. 148 149**System capability**: SystemCapability.Communication.NetStack 150 151**Parameters** 152 153| Name | Type | Mandatory| Description | 154| -------- | ---------------------------------------------- | ---- | ---------------------- | 155| url | string | Yes | URL for initiating an HTTP request.| 156| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | 157 158**Error codes** 159 160| ID | Error Message | 161|---------|----------------------------------------------------------------| 162| 401 | Parameter error. | 163| 201 | Permission denied. | 164| 2300001 | Unsupported protocol. | 165| 2300003 | Invalid URL format or missing URL. | 166| 2300005 | Failed to resolve the proxy name. | 167| 2300006 | Failed to resolve the host name. | 168| 2300007 | Failed to connect to the server. | 169| 2300008 | Invalid server response. | 170| 2300009 | Access to the remote resource denied. | 171| 2300016 | Error in the HTTP2 framing layer. | 172| 2300018 | Transferred a partial file. | 173| 2300023 | Failed to write the received data to the disk or application. | 174| 2300025 | Upload failed. | 175| 2300026 | Failed to open or read local data from the file or application.| 176| 2300027 | Out of memory. | 177| 2300028 | Operation timeout. | 178| 2300047 | The number of redirections reaches the maximum allowed. | 179| 2300052 | The server returned nothing (no header or data). | 180| 2300055 | Failed to send data to the peer. | 181| 2300056 | Failed to receive data from the peer. | 182| 2300058 | Local SSL certificate error. | 183| 2300059 | The specified SSL cipher cannot be used. | 184| 2300060 | Invalid SSL peer certificate or SSH remote key. | 185| 2300061 | Invalid HTTP encoding format. | 186| 2300063 | Maximum file size exceeded. | 187| 2300070 | Remote disk full. | 188| 2300073 | Remote file already exists. | 189| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 190| 2300078 | Remote file not found. | 191| 2300094 | Authentication error. | 192| 2300997 | Cleartext traffic not permitted. | 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 can receive only data whose size is less than 5 MB. If the data size exceeds 5 MB, you need to set **maxLimit** to a larger value in **HttpRequestOptions**. 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| 2300997 | Cleartext traffic not permitted. | 279| 2300998 | It is not allowed to access this domain. | 280| 2300999 | Unknown error. | 281 282> **NOTE** 283> For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [HTTP Error Codes](errorcode-net-http.md). 284> 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). 285 286**Example** 287 288```ts 289import { http } from '@kit.NetworkKit'; 290 291class Header { 292 public contentType: string; 293 294 constructor(contentType: string) { 295 this.contentType = contentType; 296 } 297} 298 299let httpRequest = http.createHttp(); 300let options: http.HttpRequestOptions = { 301 method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. 302 // This field is used to transfer the request body when a POST request is used. Its format needs to be negotiated with the server. 303 extraData: 'data to send', 304 expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data. 305 usingCache: true, // Optional. The default value is true. 306 priority: 1, // Optional. The default value is 1. 307 // You can add header fields based on service requirements. 308 header: new Header('application/json'), 309 readTimeout: 60000, // Optional. The default value is 60000, in ms. 310 connectTimeout: 60000 // Optional. The default value is 60000, in ms. 311 usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. 312 usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API version 10. 313}; 314 315httpRequest.request("EXAMPLE_URL", options, (err: Error, data: http.HttpResponse) => { 316 if (!err) { 317 console.info('Result:' + data.result); 318 console.info('code:' + data.responseCode); 319 console.info('type:' + JSON.stringify(data.resultType)); 320 console.info('header:' + JSON.stringify(data.header)); 321 console.info('cookies:' + data.cookies); // Cookies are supported since API version 8. 322 } else { 323 console.info('error:' + JSON.stringify(err)); 324 } 325}); 326``` 327 328### request 329 330request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\> 331 332Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. 333 334> **NOTE** 335> This API can receive only data whose size is less than 5 MB. If the data size exceeds 5 MB, you need to set **maxLimit** to a larger value in **HttpRequestOptions**. 336> 337> If you need to pass in cookies, add them to the **options** parameter. 338 339**Required permissions**: ohos.permission.INTERNET 340 341**Atomic service API**: This API can be used in atomic services since API version 11. 342 343**System capability**: SystemCapability.Communication.NetStack 344 345**Parameters** 346 347| Name | Type | Mandatory| Description | 348| ------- | ------------------ | ---- | ----------------------------------------------- | 349| url | string | Yes | URL for initiating an HTTP request. | 350| options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 351 352**Return value** 353 354| Type | Description | 355| :------------------------------------- | :-------------------------------- | 356| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| 357 358**Error codes** 359 360| ID | Error Message | 361|---------|----------------------------------------------------------------| 362| 401 | Parameter error. | 363| 201 | Permission denied. | 364| 2300001 | Unsupported protocol. | 365| 2300003 | Invalid URL format or missing URL. | 366| 2300005 | Failed to resolve the proxy name. | 367| 2300006 | Failed to resolve the host name. | 368| 2300007 | Failed to connect to the server. | 369| 2300008 | Invalid server response. | 370| 2300009 | Access to the remote resource denied. | 371| 2300016 | Error in the HTTP2 framing layer. | 372| 2300018 | Transferred a partial file. | 373| 2300023 | Failed to write the received data to the disk or application. | 374| 2300025 | Upload failed. | 375| 2300026 | Failed to open or read local data from the file or application.| 376| 2300027 | Out of memory. | 377| 2300028 | Operation timeout. | 378| 2300047 | The number of redirections reaches the maximum allowed. | 379| 2300052 | The server returned nothing (no header or data). | 380| 2300055 | Failed to send data to the peer. | 381| 2300056 | Failed to receive data from the peer. | 382| 2300058 | Local SSL certificate error. | 383| 2300059 | The specified SSL cipher cannot be used. | 384| 2300060 | Invalid SSL peer certificate or SSH remote key. | 385| 2300061 | Invalid HTTP encoding format. | 386| 2300063 | Maximum file size exceeded. | 387| 2300070 | Remote disk full. | 388| 2300073 | Remote file already exists. | 389| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 390| 2300078 | Remote file not found. | 391| 2300094 | Authentication error. | 392| 2300997 | Cleartext traffic not permitted. | 393| 2300998 | It is not allowed to access this domain. | 394| 2300999 | Unknown error. | 395 396> **NOTE** 397> For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [HTTP Error Codes](errorcode-net-http.md). 398> 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). 399 400**Example** 401 402```ts 403import { http } from '@kit.NetworkKit'; 404 405class Header { 406 public contentType: string; 407 408 constructor(contentType: string) { 409 this.contentType = contentType; 410 } 411} 412 413let httpRequest = http.createHttp(); 414let promise = httpRequest.request("EXAMPLE_URL", { 415 method: http.RequestMethod.GET, 416 connectTimeout: 60000, 417 readTimeout: 60000, 418 header: new Header('application/json') 419}); 420promise.then((data:http.HttpResponse) => { 421 console.info('Result:' + data.result); 422 console.info('code:' + data.responseCode); 423 console.info('type:' + JSON.stringify(data.resultType)); 424 console.info('header:' + JSON.stringify(data.header)); 425 console.info('cookies:' + data.cookies); // Cookies are supported since API version 8. 426 console.info('header.content-Type:' + data.header); 427 console.info('header.Status-Line:' + data.header); 428}).catch((err:Error) => { 429 console.info('error:' + JSON.stringify(err)); 430}); 431``` 432 433### destroy 434 435destroy(): void 436 437Destroys an HTTP request. 438 439**Atomic service API**: This API can be used in atomic services since API version 11. 440 441**System capability**: SystemCapability.Communication.NetStack 442 443**Example** 444 445```ts 446import { http } from '@kit.NetworkKit'; 447let httpRequest = http.createHttp(); 448 449httpRequest.destroy(); 450``` 451 452### requestInStream<sup>10+</sup> 453 454requestInStream(url: string, callback: AsyncCallback\<number\>): void 455 456Initiates 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. 457 458**Required permissions**: ohos.permission.INTERNET 459 460**System capability**: SystemCapability.Communication.NetStack 461 462**Parameters** 463 464| Name | Type | Mandatory| Description | 465| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 466| url | string | Yes | URL for initiating an HTTP request. | 467| callback | AsyncCallback\<number\> | Yes | Callback used to return the result. | 468 469**Error codes** 470 471| ID | Error Message | 472|---------|----------------------------------------------------------------| 473| 401 | Parameter error. | 474| 201 | Permission denied. | 475| 2300001 | Unsupported protocol. | 476| 2300003 | Invalid URL format or missing URL. | 477| 2300005 | Failed to resolve the proxy name. | 478| 2300006 | Failed to resolve the host name. | 479| 2300007 | Failed to connect to the server. | 480| 2300008 | Invalid server response. | 481| 2300009 | Access to the remote resource denied. | 482| 2300016 | Error in the HTTP2 framing layer. | 483| 2300018 | Transferred a partial file. | 484| 2300023 | Failed to write the received data to the disk or application. | 485| 2300025 | Upload failed. | 486| 2300026 | Failed to open or read local data from the file or application.| 487| 2300027 | Out of memory. | 488| 2300028 | Operation timeout. | 489| 2300047 | The number of redirections reaches the maximum allowed. | 490| 2300052 | The server returned nothing (no header or data). | 491| 2300055 | Failed to send data to the peer. | 492| 2300056 | Failed to receive data from the peer. | 493| 2300058 | Local SSL certificate error. | 494| 2300059 | The specified SSL cipher cannot be used. | 495| 2300060 | Invalid SSL peer certificate or SSH remote key. | 496| 2300061 | Invalid HTTP encoding format. | 497| 2300063 | Maximum file size exceeded. | 498| 2300070 | Remote disk full. | 499| 2300073 | Remote file already exists. | 500| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 501| 2300078 | Remote file not found. | 502| 2300094 | Authentication error. | 503| 2300997 | Cleartext traffic not permitted. | 504| 2300998 | It is not allowed to access this domain. | 505| 2300999 | Unknown error. | 506 507> **NOTE** 508> For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [HTTP Error Codes](errorcode-net-http.md). 509> 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). 510 511**Example** 512 513```ts 514import { http } from '@kit.NetworkKit'; 515import { BusinessError } from '@kit.BasicServicesKit'; 516 517let httpRequest = http.createHttp(); 518httpRequest.requestInStream("EXAMPLE_URL", (err: BusinessError, data: number) => { 519 if (!err) { 520 console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); 521 } else { 522 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 523 } 524}) 525``` 526 527### requestInStream<sup>10+</sup> 528 529requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void 530 531Initiates 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. 532 533**Required permissions**: ohos.permission.INTERNET 534 535**System capability**: SystemCapability.Communication.NetStack 536 537**Parameters** 538 539| Name | Type | Mandatory| Description | 540| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 541| url | string | Yes | URL for initiating an HTTP request. | 542| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 543| callback | AsyncCallback\<[number](#responsecode)\> | Yes | Callback used to return the result. | 544 545**Error codes** 546 547| ID | Error Message | 548|---------|----------------------------------------------------------------| 549| 401 | Parameter error. | 550| 201 | Permission denied. | 551| 2300001 | Unsupported protocol. | 552| 2300003 | Invalid URL format or missing URL. | 553| 2300005 | Failed to resolve the proxy name. | 554| 2300006 | Failed to resolve the host name. | 555| 2300007 | Failed to connect to the server. | 556| 2300008 | Invalid server response. | 557| 2300009 | Access to the remote resource denied. | 558| 2300016 | Error in the HTTP2 framing layer. | 559| 2300018 | Transferred a partial file. | 560| 2300023 | Failed to write the received data to the disk or application. | 561| 2300025 | Upload failed. | 562| 2300026 | Failed to open or read local data from the file or application.| 563| 2300027 | Out of memory. | 564| 2300028 | Operation timeout. | 565| 2300047 | The number of redirections reaches the maximum allowed. | 566| 2300052 | The server returned nothing (no header or data). | 567| 2300055 | Failed to send data to the peer. | 568| 2300056 | Failed to receive data from the peer. | 569| 2300058 | Local SSL certificate error. | 570| 2300059 | The specified SSL cipher cannot be used. | 571| 2300060 | Invalid SSL peer certificate or SSH remote key. | 572| 2300061 | Invalid HTTP encoding format. | 573| 2300063 | Maximum file size exceeded. | 574| 2300070 | Remote disk full. | 575| 2300073 | Remote file already exists. | 576| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 577| 2300078 | Remote file not found. | 578| 2300094 | Authentication error. | 579| 2300997 | Cleartext traffic not permitted. | 580| 2300998 | It is not allowed to access this domain. | 581| 2300999 | Unknown error. | 582 583> **NOTE** 584> For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [HTTP Error Codes](errorcode-net-http.md). 585> 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). 586 587**Example** 588 589```ts 590import { http } from '@kit.NetworkKit'; 591import { BusinessError } from '@kit.BasicServicesKit'; 592 593class Header { 594 public contentType: string; 595 596 constructor(contentType: string) { 597 this.contentType = contentType; 598 } 599} 600 601let httpRequest = http.createHttp(); 602let options: http.HttpRequestOptions = { 603 method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. 604 // This field is used to transfer the request body when a POST request is used. Its format needs to be negotiated with the server. 605 extraData: 'data to send', 606 expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data. 607 usingCache: true, // Optional. The default value is true. 608 priority: 1, // Optional. The default value is 1. 609 // You can add header fields based on service requirements. 610 header: new Header('application/json'), 611 readTimeout: 60000, // Optional. The default value is 60000, in ms. 612 connectTimeout: 60000 // Optional. The default value is 60000, in ms. 613 usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. 614 usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API version 10. 615}; 616httpRequest.requestInStream("EXAMPLE_URL", options, (err: BusinessError<void> , data: number) => { 617 if (!err) { 618 console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); 619 } else { 620 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 621 } 622}) 623``` 624 625### requestInStream<sup>10+</sup> 626 627requestInStream(url: string, options? : HttpRequestOptions): Promise\<number\> 628 629Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response. 630 631**Required permissions**: ohos.permission.INTERNET 632 633**System capability**: SystemCapability.Communication.NetStack 634 635**Parameters** 636 637| Name | Type | Mandatory| Description | 638| ------- | ------------------ | ---- | ----------------------------------------------- | 639| url | string | Yes | URL for initiating an HTTP request. | 640| options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 641 642**Return value** 643 644| Type | Description | 645| :------------------------------------- | :-------------------------------- | 646| Promise\<[number](#responsecode)\> | Promise used to return the result.| 647 648**Error codes** 649 650| ID | Error Message | 651|---------|----------------------------------------------------------------| 652| 401 | Parameter error. | 653| 201 | Permission denied. | 654| 2300001 | Unsupported protocol. | 655| 2300003 | Invalid URL format or missing URL. | 656| 2300005 | Failed to resolve the proxy name. | 657| 2300006 | Failed to resolve the host name. | 658| 2300007 | Failed to connect to the server. | 659| 2300008 | Invalid server response. | 660| 2300009 | Access to the remote resource denied. | 661| 2300016 | Error in the HTTP2 framing layer. | 662| 2300018 | Transferred a partial file. | 663| 2300023 | Failed to write the received data to the disk or application. | 664| 2300025 | Upload failed. | 665| 2300026 | Failed to open or read local data from the file or application.| 666| 2300027 | Out of memory. | 667| 2300028 | Operation timeout. | 668| 2300047 | The number of redirections reaches the maximum allowed. | 669| 2300052 | The server returned nothing (no header or data). | 670| 2300055 | Failed to send data to the peer. | 671| 2300056 | Failed to receive data from the peer. | 672| 2300058 | Local SSL certificate error. | 673| 2300059 | The specified SSL cipher cannot be used. | 674| 2300060 | Invalid SSL peer certificate or SSH remote key. | 675| 2300061 | Invalid HTTP encoding format. | 676| 2300063 | Maximum file size exceeded. | 677| 2300070 | Remote disk full. | 678| 2300073 | Remote file already exists. | 679| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 680| 2300078 | Remote file not found. | 681| 2300094 | Authentication error. | 682| 2300997 | Cleartext traffic not permitted. | 683| 2300998 | It is not allowed to access this domain. | 684| 2300999 | Unknown error. | 685 686> **NOTE** 687> For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [HTTP Error Codes](errorcode-net-http.md). 688> 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). 689 690**Example** 691 692```ts 693import { http } from '@kit.NetworkKit'; 694 695class Header { 696 public contentType: string; 697 698 constructor(contentType: string) { 699 this.contentType = contentType; 700 } 701} 702 703let httpRequest = http.createHttp(); 704let promise = httpRequest.requestInStream("EXAMPLE_URL", { 705 method: http.RequestMethod.GET, 706 connectTimeout: 60000, 707 readTimeout: 60000, 708 header: new Header('application/json') 709}); 710promise.then((data: number) => { 711 console.info("requestInStream OK!" + data); 712}).catch((err: Error) => { 713 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 714}); 715``` 716 717### on("headerReceive")<sup>(deprecated)</sup> 718 719on(type: "headerReceive", callback: AsyncCallback\<Object\>): void 720 721Registers an observer for HTTP Response Header events. 722 723> **NOTE** 724> This API has been deprecated. You are advised to use [on("headersReceive")<sup>8+</sup>](#onheadersreceive8). 725 726**System capability**: SystemCapability.Communication.NetStack 727 728**Parameters** 729 730| Name | Type | Mandatory| Description | 731| -------- | ----------------------- | ---- | --------------------------------- | 732| type | string | Yes | Event type. The value is **headerReceive**.| 733| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. | 734 735**Example** 736 737```ts 738import { http } from '@kit.NetworkKit'; 739import { BusinessError } from '@kit.BasicServicesKit'; 740 741let httpRequest = http.createHttp(); 742httpRequest.on("headerReceive", (data: BusinessError) => { 743 console.info("error:" + JSON.stringify(data)); 744}); 745``` 746 747### off("headerReceive")<sup>(deprecated)</sup> 748 749off(type: "headerReceive", callback?: AsyncCallback\<Object\>): void 750 751Unregisters the observer for HTTP Response Header events. 752 753> **NOTE** 754> 755>- This API has been deprecated. You are advised to use [off("headersReceive")<sup>8+</sup>](#offheadersreceive8). 756> 757>- 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. 758 759**System capability**: SystemCapability.Communication.NetStack 760 761**Parameters** 762 763| Name | Type | Mandatory| Description | 764| -------- | ----------------------- | ---- | ------------------------------------- | 765| type | string | Yes | Event type. The value is **headerReceive**.| 766| callback | AsyncCallback\<Object\> | No | Callback used to return the result. | 767 768**Example** 769 770```ts 771import { http } from '@kit.NetworkKit'; 772 773let httpRequest = http.createHttp(); 774httpRequest.off("headerReceive"); 775``` 776 777### on("headersReceive")<sup>8+</sup> 778 779on(type: "headersReceive", callback: Callback\<Object\>): void 780 781Registers an observer for HTTP Response Header events. 782 783**Atomic service API**: This API can be used in atomic services since API version 11. 784 785**System capability**: SystemCapability.Communication.NetStack 786 787**Parameters** 788 789| Name | Type | Mandatory| Description | 790| -------- | ------------------ | ---- | ---------------------------------- | 791| type | string | Yes | Event type. The value is **headersReceive**.| 792| callback | Callback\<Object\> | Yes | Callback used to return the result. | 793 794**Example** 795 796```ts 797import { http } from '@kit.NetworkKit'; 798 799let httpRequest = http.createHttp(); 800httpRequest.on("headersReceive", (header: Object) => { 801 console.info("header: " + JSON.stringify(header)); 802}); 803httpRequest.off("headersReceive"); 804``` 805 806### off("headersReceive")<sup>8+</sup> 807 808off(type: "headersReceive", callback?: Callback\<Object\>): void 809 810Unregisters the observer for HTTP Response Header events. 811 812> **NOTE** 813> 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. 814 815**Atomic service API**: This API can be used in atomic services since API version 11. 816 817**System capability**: SystemCapability.Communication.NetStack 818 819**Parameters** 820 821| Name | Type | Mandatory| Description | 822| -------- | ------------------ | ---- | -------------------------------------- | 823| type | string | Yes | Event type. The value is **headersReceive**.| 824| callback | Callback\<Object\> | No | Callback used to return the result. | 825 826**Example** 827 828```ts 829import { http } from '@kit.NetworkKit'; 830 831let httpRequest = http.createHttp(); 832httpRequest.on("headersReceive", (header: Object) => { 833 console.info("header: " + JSON.stringify(header)); 834}); 835httpRequest.off("headersReceive"); 836``` 837 838### once("headersReceive")<sup>8+</sup> 839 840once(type: "headersReceive", callback: Callback\<Object\>): void 841 842Registers 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. 843 844**System capability**: SystemCapability.Communication.NetStack 845 846**Parameters** 847 848| Name | Type | Mandatory| Description | 849| -------- | ------------------ | ---- | ---------------------------------- | 850| type | string | Yes | Event type. The value is **headersReceive**.| 851| callback | Callback\<Object\> | Yes | Callback used to return the result. | 852 853**Example** 854 855```ts 856import { http } from '@kit.NetworkKit'; 857 858let httpRequest = http.createHttp(); 859httpRequest.once("headersReceive", (header: Object) => { 860 console.info("header: " + JSON.stringify(header)); 861}); 862``` 863 864### on("dataReceive")<sup>10+</sup> 865 866on(type: "dataReceive", callback: Callback\<ArrayBuffer\>): void 867 868Registers an observer for events indicating receiving of HTTP streaming responses. 869 870**System capability**: SystemCapability.Communication.NetStack 871 872**Parameters** 873 874| Name | Type | Mandatory| Description | 875| -------- | ----------------------- | ---- | --------------------------------- | 876| type | string | Yes | Event type. The value is **dataReceive**.| 877| callback | AsyncCallback\<ArrayBuffer\> | Yes | Callback used to return the result. | 878 879**Example** 880 881```ts 882import { http } from '@kit.NetworkKit'; 883 884let httpRequest = http.createHttp(); 885httpRequest.on("dataReceive", (data: ArrayBuffer) => { 886 console.info("dataReceive length: " + JSON.stringify(data.byteLength)); 887}); 888httpRequest.off("dataReceive"); 889``` 890 891### off("dataReceive")<sup>10+</sup> 892 893off(type: "dataReceive", callback?: Callback\<ArrayBuffer\>): void 894 895Unregisters the observer for events indicating receiving of HTTP streaming responses. 896 897> **NOTE** 898> 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. 899 900**System capability**: SystemCapability.Communication.NetStack 901 902**Parameters** 903 904| Name | Type | Mandatory| Description | 905| -------- | ------------------ | ---- | -------------------------------------- | 906| type | string | Yes | Event type. The value is **dataReceive**.| 907| callback | Callback\<ArrayBuffer\> | No | Callback used to return the result. | 908 909**Example** 910 911```ts 912import { http } from '@kit.NetworkKit'; 913 914let httpRequest = http.createHttp(); 915httpRequest.on("dataReceive", (data: ArrayBuffer) => { 916 console.info("dataReceive length: " + JSON.stringify(data.byteLength)); 917}); 918httpRequest.off("dataReceive"); 919``` 920 921### on("dataEnd")<sup>10+</sup> 922 923on(type: "dataEnd", callback: Callback\<void\>): void 924 925Registers an observer for events indicating completion of receiving HTTP streaming responses. 926 927**System capability**: SystemCapability.Communication.NetStack 928 929**Parameters** 930 931| Name | Type | Mandatory| Description | 932| -------- | ----------------------- | ---- | --------------------------------- | 933| type | string | Yes | Event type. The value is **dataEnd**.| 934| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 935 936**Example** 937 938```ts 939import { http } from '@kit.NetworkKit'; 940 941let httpRequest = http.createHttp(); 942httpRequest.on("dataEnd", () => { 943 console.info("Receive dataEnd !"); 944}); 945httpRequest.off("dataEnd"); 946``` 947 948### off("dataEnd")<sup>10+</sup> 949 950off(type: "dataEnd", callback?: Callback\<void\>): void 951 952Unregisters the observer for events indicating completion of receiving HTTP streaming responses. 953 954> **NOTE** 955> 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. 956 957**System capability**: SystemCapability.Communication.NetStack 958 959**Parameters** 960 961| Name | Type | Mandatory| Description | 962| -------- | ------------------ | ---- | -------------------------------------- | 963| type | string | Yes | Event type. The value is **dataEnd**.| 964| callback | Callback\<void\> | No | Callback used to return the result. | 965 966**Example** 967 968```ts 969import { http } from '@kit.NetworkKit'; 970 971let httpRequest = http.createHttp(); 972httpRequest.on("dataEnd", () => { 973 console.info("Receive dataEnd !"); 974}); 975httpRequest.off("dataEnd"); 976``` 977 978### on('dataReceiveProgress')<sup>10+</sup> 979 980on(type: 'dataReceiveProgress', callback: Callback\<DataReceiveProgressInfo\>): void 981 982Registers an observer for events indicating progress of receiving HTTP streaming responses. 983 984**System capability**: SystemCapability.Communication.NetStack 985 986**Parameters** 987 988| Name | Type | Mandatory| Description | 989| -------- | ----------------------- | ---- | --------------------------------- | 990| type | string | Yes | Event type. The value is **dataReceiveProgress**.| 991| callback | AsyncCallback\<[DataReceiveProgressInfo](#datareceiveprogressinfo11)\> | Yes | Callback used to return the result. | 992 993**Example** 994 995```ts 996import { http } from '@kit.NetworkKit'; 997 998let httpRequest = http.createHttp(); 999httpRequest.on("dataReceiveProgress", (data: http.DataReceiveProgressInfo) => { 1000 console.info("dataReceiveProgress:" + JSON.stringify(data)); 1001}); 1002httpRequest.off("dataReceiveProgress"); 1003``` 1004 1005### off('dataReceiveProgress')<sup>10+</sup> 1006 1007off(type: 'dataReceiveProgress', callback?: Callback\<DataReceiveProgressInfo\>): void 1008 1009Unregisters the observer for events indicating progress of receiving HTTP streaming responses. 1010 1011> **NOTE** 1012> 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. 1013 1014**System capability**: SystemCapability.Communication.NetStack 1015 1016**Parameters** 1017 1018| Name | Type | Mandatory| Description | 1019| -------- | ------------------ | ---- | -------------------------------------- | 1020| type | string | Yes | Event type. The value is **dataReceiveProgress**.| 1021| callback | Callback\<[DataReceiveProgressInfo](#datareceiveprogressinfo11)\> | No | Callback used to return the result. | 1022 1023**Example** 1024 1025```ts 1026import { http } from '@kit.NetworkKit'; 1027 1028let httpRequest = http.createHttp(); 1029httpRequest.on("dataReceiveProgress", (data: http.DataReceiveProgressInfo) => { 1030 console.info("dataReceiveProgress:" + JSON.stringify(data)); 1031}); 1032httpRequest.off("dataReceiveProgress"); 1033``` 1034 1035### on('dataSendProgress')<sup>11+</sup> 1036 1037on(type: 'dataSendProgress', callback: Callback\<DataSendProgressInfo\>): void 1038 1039Registers an observer for events indicating progress of sending HTTP requests. 1040 1041**Atomic service API**: This API can be used in atomic services since API version 15. 1042 1043**System capability**: SystemCapability.Communication.NetStack 1044 1045**Parameters** 1046 1047| Name | Type | Mandatory| Description | 1048| -------- | ----------------------- | ---- | --------------------------------- | 1049| type | string | Yes | Event type. The value is **dataSendProgress**.| 1050| callback | AsyncCallback\<[DataSendProgressInfo](#datasendprogressinfo11)\> | Yes | Callback used to return the result. | 1051 1052**Example** 1053 1054```ts 1055import { http } from '@kit.NetworkKit'; 1056 1057let httpRequest = http.createHttp(); 1058httpRequest.on("dataSendProgress", (data: http.DataSendProgressInfo) => { 1059 console.info("dataSendProgress:" + JSON.stringify(data)); 1060}); 1061httpRequest.off("dataSendProgress"); 1062``` 1063 1064### off('dataSendProgress')<sup>11+</sup> 1065 1066off(type: 'dataSendProgress', callback?: Callback\<DataSendProgressInfo\>): void 1067 1068Unregisters the observer for events indicating progress of sending HTTP requests. 1069 1070> **NOTE** 1071> 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. 1072 1073**Atomic service API**: This API can be used in atomic services since API version 15. 1074 1075**System capability**: SystemCapability.Communication.NetStack 1076 1077**Parameters** 1078 1079| Name | Type | Mandatory| Description | 1080| -------- | ------------------ | ---- | -------------------------------------- | 1081| type | string | Yes | Event type. The value is **dataSendProgress**.| 1082| callback | Callback\<[DataSendProgressInfo](#datasendprogressinfo11)\> | No| Callback used to return the result. | 1083 1084**Example** 1085 1086```ts 1087import { http } from '@kit.NetworkKit'; 1088 1089let httpRequest = http.createHttp(); 1090httpRequest.on("dataSendProgress", (data: http.DataSendProgressInfo) => { 1091 console.info("dataSendProgress:" + JSON.stringify(data)); 1092}); 1093httpRequest.off("dataSendProgress"); 1094``` 1095 1096## HttpRequestOptions 1097 1098Specifies the type and value range of the optional parameters in the HTTP request. 1099 1100**System capability**: SystemCapability.Communication.NetStack 1101 1102| Name | Type | Mandatory| Description | 1103| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 1104| 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. | 1105| 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.<br>(1) 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.<br>(2) If **content-Type** is **text/xml**, this field is usually in the String format.<br>(3) If **content-Type** is **application/json**, this field is usually in the Object format.<br>(4) If **content-Type** is **application/octet-stream**, this field is usually in the ArrayBuffer format.<br>(5) If **content-Type** is **multipart/form-data** and the content to be uploaded is a file, this field is usually in the ArrayBuffer format.<br>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.| 1106| 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.| 1107| 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. | 1108| 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. | 1109| 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. | 1110| 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.| 1111| 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. | 1112| 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. | 1113| 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.| 1114| caPath<sup>10+</sup> | string | No | Path of the CA certificate. If this parameter is set, the system uses the CA certificate in the specified path. Otherwise, the system uses the preset CA certificate.<br>The preset CA certificate is available at **/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. | 1115| resumeFrom<sup>11+</sup> | number | No| Download start position. This field can be used only for the GET method. As stipulated in section 3.1 of RFC 7233, servers are allowed to ignore range requests.<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.| 1116| resumeTo<sup>11+</sup> | number | No| Download end position. This field can be used only for the GET method. As stipulated in section 3.1 of RFC 7233, servers are allowed to ignore range requests.<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.| 1117| clientCert<sup>11+</sup> | [ClientCert](#clientcert11) | No| Client certificate.| 1118| 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".| 1119| 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.| 1120| maxLimit<sup>11+</sup> | number | No| Maximum number of bytes in a response. The default value is 5\*1024\*1024, in bytes. The maximum value is **100\*1024\*1024**. | 1121| multiFormDataList<sup>11+</sup> | Array<[MultiFormData](#multiformdata11)> | No| Form data list. This field is valid when **content-Type** is set to **multipart/form-data**.| 1122| certificatePinning<sup>12+</sup> | [CertificatePinning](#certificatepinning12) \| CertificatePinning[] | No| Dynamic configuration of certificate pinning. One or more certificate PINs can be specified.| 1123| addressFamily<sup>15+</sup> | [AddressFamily](#addressfamily15) | No| IP address family. You can specify an address type for domain name resolution.| 1124| remoteValidation<sup>18+</sup> | [RemoteValidation](#remotevalidation18) | No| Certificate authority (CA), which is used to verify the identity of a remote server. If the parameter is not set, the default value is used. The options are as follows:<br>**Atomic service API**: This API can be used in atomic services since API version 18. | 1125| tlsOptions<sup>18+</sup> | [TlsOptions](#tlsoptions18) | No| TLS configuration.<br>**Atomic service API**: This API can be used in atomic services since API version 18. | 1126| serverAuthentication<sup>18+</sup> | [ServerAuthentication](#serverauthentication18) | No| Indicates whether to verify the server identity during a secure connection. The identity is not verified by default.<br>**Atomic service API**: This API can be used in atomic services since API version 18. | 1127 1128## RequestMethod 1129 1130Defines an HTTP request method. 1131 1132**Atomic service API**: This API can be used in atomic services since API version 11. 1133 1134**System capability**: SystemCapability.Communication.NetStack 1135 1136| Name | Value | Description | 1137| :------ | ------- | :------------------ | 1138| OPTIONS | "OPTIONS" | Describes the communication options of the target resource.| 1139| GET | "GET" | Requests the representation of the specified resource. The GET request should only retrieve data and should not contain the request content.| 1140| HEAD | "HEAD" | Requests the same response (but does not have a response body) as the GET request.| 1141| POST | "POST" | Submits an entity to a specified resource, which usually causes a status change on the server.| 1142| PUT | "PUT" | Replaces all current representations of the target resource with the requested content.| 1143| DELETE | "DELETE" | Deletes the specified resource.| 1144| TRACE | "TRACE" | Performs a message loopback test along the path to the target resource.| 1145| CONNECT | "CONNECT" | Establishes a tunnel to the server identified by the target resource.| 1146 1147## ResponseCode 1148 1149Enumerates the response codes for an HTTP request. 1150 1151**System capability**: SystemCapability.Communication.NetStack 1152 1153| Name | Value | Description | 1154| ----------------- | ---- | ------------------------------------------------------------ | 1155| OK | 200 | The request is successful. 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. | 1156| 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. | 1157| ACCEPTED | 202 | "Accepted." The request has been accepted for processing, but the processing has not been completed.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 1158| 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. | 1159| 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. | 1160| 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. | 1161| 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. | 1162| 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. | 1163| 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.| 1164| 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. | 1165| 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. | 1166| 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. | 1167| 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. | 1168| 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. | 1169| UNAUTHORIZED | 401 | "Unauthorized." The request requires user authentication.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 1170| 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. | 1171| 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. | 1172| 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. | 1173| 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. | 1174| 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. | 1175| 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. | 1176| 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. | 1177| 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.| 1178| 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. | 1179| 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. | 1180| 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. | 1181| 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. | 1182| 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. | 1183| 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. | 1184| 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. | 1185| 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. | 1186| 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. | 1187| 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.| 1188| 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. | 1189| 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. | 1190| 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. | 1191 1192## HttpResponse 1193 1194Defines the response to an HTTP request. 1195 1196**System capability**: SystemCapability.Communication.NetStack 1197 1198| Name | Type | Mandatory| Description | 1199| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 1200| 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.| 1201| 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. | 1202| 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.| 1203| 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.| 1204| 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. | 1205| performanceTiming<sup>11+</sup> | [PerformanceTiming](#performancetiming11) | Yes| Time consumed in each phase of an HTTP request.| 1206 1207## ClientCert<sup>11+</sup> 1208 1209Defines the client certificate type. 1210 1211**System capability**: SystemCapability.Communication.NetStack 1212 1213| Name| Type| Mandatory| Description| 1214| -------- | -------| --- | ----------- | 1215| certPath | string | Yes| Certificate path.| 1216| certType | [CertType](#certtype11) | No| Certificate type. The default value is **PEM**.| 1217| keyPath | string | Yes| Path of the certificate key file.| 1218| keyPassword | string | No | Password of the certificate key file.| 1219 1220## PerformanceTiming<sup>11+</sup> 1221 1222Configures the timing for performance tracing, in ms. 1223 1224**System capability**: SystemCapability.Communication.NetStack 1225 1226| Name | Type | Mandatory | Description | 1227| ---------- | ------ | ---- | --------------------- | 1228| dnsTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the DNS resolution is complete.| 1229| tcpTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the TCP connection is complete.| 1230| tlsTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the TLS connection is complete.| 1231| firstSendTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the first byte is sent.| 1232| firstReceiveTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the first byte is received.| 1233| totalFinishTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the request is complete.| 1234| redirectTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when all redirection steps are complete.| 1235| responseHeaderTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the header resolution is complete.| 1236| responseBodyTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the body resolution is complete.| 1237| totalTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when a callback is returned to the application.| 1238 1239## DataReceiveProgressInfo<sup>11+</sup> 1240 1241Defines the data receiving progress information. 1242 1243**System capability**: SystemCapability.Communication.NetStack 1244 1245| Name| Type| Mandatory| Description| 1246| ---- | ---- | ---- | ---- | 1247| receiveSize | number | Yes | Size of data that has been received, in bytes. | 1248| totalSize| number | Yes| Total size of data to be received, in bytes.| 1249 1250## DataSendProgressInfo<sup>11+</sup> 1251 1252Defines the data sending progress information. 1253 1254**Atomic service API**: This API can be used in atomic services since API version 15. 1255 1256**System capability**: SystemCapability.Communication.NetStack 1257 1258### Attributes 1259 1260| Name| Type| Mandatory| Description| 1261| ---- | ---- | ---- | ---- | 1262| sendSize | number | Yes | Size of data to be sent, in bytes. | 1263| totalSize | number | Yes| Total size of data to be sent, in bytes.| 1264 1265## MultiFormData<sup>11+</sup> 1266 1267Defines the type of multi-form data. 1268 1269**System capability**: SystemCapability.Communication.NetStack 1270 1271| Name| Type| Mandatory| Description| 1272| ---- | ---- | ---- | ---- | 1273| name | string | Yes | Data name. | 1274| contentType | string | Yes| Data type, for example, **text/plain**, **image/png**, **image/jpeg**, **audio/mpeg**, or **video/mp4**.| 1275| remoteFileName | string | No| Name of the file uploaded to the server. | 1276| data | string \| Object \| ArrayBuffer | No| Form data content. | 1277| 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.| 1278 1279## http.createHttpResponseCache<sup>9+</sup> 1280 1281createHttpResponseCache(cacheSize?: number): HttpResponseCache 1282 1283Creates 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. 1284 1285**Atomic service API**: This API can be used in atomic services since API version 11. 1286 1287**System capability**: SystemCapability.Communication.NetStack 1288 1289**Parameters** 1290 1291| Name | Type | Mandatory| Description | 1292| -------- | --------------------------------------- | ---- | ---------- | 1293| cacheSize | number | No| Cache size. The maximum value is 10\*1024\*1024 (10 MB). By default, the maximum value is used.| 1294 1295**Return value** 1296 1297| Type | Description | 1298| :---------- | :----------------------------------------------------------- | 1299| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.| 1300 1301**Example** 1302 1303```ts 1304import { http } from '@kit.NetworkKit'; 1305 1306let httpResponseCache = http.createHttpResponseCache(); 1307``` 1308 1309## HttpResponseCache<sup>9+</sup> 1310 1311Defines 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. 1312 1313**Usage of Keywords in the Response Header** 1314 1315- **`Cache-Control`**: specifies the cache policy, for example, `no-cache`, `no-store`, `max-age`, `public`, or `private`. 1316 1317- **`Expires`**: specifies the expiration time of a resource. The value is in the GMT format. 1318 1319- **`ETag`**: identifies the resource version. The client can use the `If-None-Match` request header to check whether the resource has been modified. 1320 1321- **`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. 1322 1323- **`Vary`**: specifies the parts of the request header that affect the cached response. This field is used to distinguish different cache versions. 1324 1325When 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. 1326 1327**How to Set the Cache-Control Header** 1328 1329`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: 1330 1331- **`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. 1332 1333- `no-store`: indicates that resources cannot be cached. Resources must be obtained from the server for each request. 1334 1335- `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). 1336 1337- `public`: indicates that the response can be cached by any object, for example, the client that sends the request or the proxy server. 1338 1339- `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). 1340 1341- `must-revalidate`: indicates that a resource must be revalidated with the origin server once it has become stable. 1342 1343- **`no-transform`**: indicates that the proxy server is not allowed to modify the response content. 1344 1345- **`proxy-revalidate`**: works in a way similar to `must-revalidate`, but applies only to shared caches. 1346 1347- **`s-maxage`**: works in a way similar to `max-age`, but applies only to shared caches. 1348 1349### flush<sup>9+</sup> 1350 1351flush(callback: AsyncCallback\<void\>): void 1352 1353Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses an asynchronous callback to return the result. Cached data includes the response header (header), response body (result), cookies, request time (requestTime), and response time (responseTime). 1354 1355**Atomic service API**: This API can be used in atomic services since API version 11. 1356 1357**System capability**: SystemCapability.Communication.NetStack 1358 1359**Parameters** 1360 1361| Name | Type | Mandatory| Description | 1362| -------- | --------------------------------------- | ---- | ---------- | 1363| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 1364 1365**Example** 1366 1367```ts 1368import { http } from '@kit.NetworkKit'; 1369import { BusinessError } from '@kit.BasicServicesKit'; 1370 1371let httpResponseCache = http.createHttpResponseCache(); 1372let httpRequest = http.createHttp(); 1373httpRequest.request("EXAMPLE_URL", (err: BusinessError, data: http.HttpResponse) => { 1374 if (!err) { 1375 httpResponseCache.flush((err: BusinessError) => { 1376 if (err) { 1377 console.error('flush fail'); 1378 } 1379 console.info('flush success'); 1380 }); 1381 httpRequest.destroy(); 1382 } else { 1383 console.error('error:' + JSON.stringify(err)); 1384 // Call destroy() to destroy the JavaScript object after the HTTP request is complete. 1385 httpRequest.destroy(); 1386 } 1387}); 1388``` 1389 1390### flush<sup>9+</sup> 1391 1392flush(): Promise\<void\> 1393 1394Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses a promise to return the result. 1395 1396**Atomic service API**: This API can be used in atomic services since API version 11. 1397 1398**System capability**: SystemCapability.Communication.NetStack 1399 1400**Return value** 1401 1402| Type | Description | 1403| --------------------------------- | ------------------------------------- | 1404| Promise\<void\> | Promise used to return the result.| 1405 1406**Example** 1407 1408```ts 1409import { http } from '@kit.NetworkKit'; 1410import { BusinessError } from '@kit.BasicServicesKit'; 1411 1412let httpRequest = http.createHttp(); 1413let httpResponseCache = http.createHttpResponseCache(); 1414let promise = httpRequest.request("EXAMPLE_URL"); 1415 1416promise.then((data: http.HttpResponse) => { 1417 httpResponseCache.flush().then(() => { 1418 console.error('flush success'); 1419 }).catch((err: BusinessError) => { 1420 console.info('flush fail'); 1421 }); 1422}).catch((err: Error) => { 1423 console.error('error:' + JSON.stringify(err)); 1424}); 1425``` 1426 1427### delete<sup>9+</sup> 1428 1429delete(callback: AsyncCallback\<void\>): void 1430 1431Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result. 1432 1433**Atomic service API**: This API can be used in atomic services since API version 11. 1434 1435**System capability**: SystemCapability.Communication.NetStack 1436 1437**Parameters** 1438 1439| Name | Type | Mandatory| Description | 1440| -------- | --------------------------------------- | ---- | ---------- | 1441| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 1442 1443**Example** 1444 1445```ts 1446import { http } from '@kit.NetworkKit'; 1447import { BusinessError } from '@kit.BasicServicesKit'; 1448 1449let httpRequest = http.createHttp(); 1450httpRequest.request("EXAMPLE_URL").then(data => { 1451 const httpResponseCache = http.createHttpResponseCache(); 1452 httpResponseCache.delete((err: BusinessError) => { 1453 try { 1454 if (err) { 1455 console.error('fail: ' + err); 1456 } else { 1457 console.info('success'); 1458 } 1459 } catch (err) { 1460 console.error('error: ' + err); 1461 } 1462 }); 1463 httpRequest.destroy(); 1464}).catch((error: BusinessError) => { 1465 console.error("errocode" + JSON.stringify(error)); 1466}); 1467``` 1468 1469### delete<sup>9+</sup> 1470 1471delete(): Promise\<void\> 1472 1473Disables the cache and deletes the data in it. This API uses a promise to return the result. 1474 1475**Atomic service API**: This API can be used in atomic services since API version 11. 1476 1477**System capability**: SystemCapability.Communication.NetStack 1478 1479**Return value** 1480 1481| Type | Description | 1482| --------------------------------- | ------------------------------------- | 1483| Promise\<void\> | Promise used to return the result.| 1484 1485**Example** 1486 1487```ts 1488import { http } from '@kit.NetworkKit'; 1489import { BusinessError } from '@kit.BasicServicesKit'; 1490 1491let httpRequest = http.createHttp(); 1492httpRequest.request("EXAMPLE_URL").then(data => { 1493 const httpResponseCache = http.createHttpResponseCache(); 1494 httpResponseCache.delete().then(() => { 1495 console.log("success"); 1496 }).catch((err: BusinessError) => { 1497 console.error("fail"); 1498 }); 1499 httpRequest.destroy(); 1500}).catch((error: BusinessError) => { 1501 console.error("errocode" + JSON.stringify(error)); 1502}); 1503``` 1504 1505## HttpDataType<sup>9+</sup> 1506 1507Enumerates HTTP data types. 1508 1509**Atomic service API**: This API can be used in atomic services since API version 11. 1510 1511**System capability**: SystemCapability.Communication.NetStack 1512 1513| Name| Value| Description | 1514| ------------------ | -- | ----------- | 1515| STRING | 0 | String type.| 1516| OBJECT | 1 | Object type. | 1517| ARRAY_BUFFER | 2 | Binary array type.| 1518 1519## HttpProtocol<sup>9+</sup> 1520 1521Enumerates HTTP protocol versions. 1522 1523**System capability**: SystemCapability.Communication.NetStack 1524 1525| Name | Value | Description | 1526| :-------- | :----------- | :----------- | 1527| HTTP1_1 | 0 | HTTP1.1<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 1528| HTTP2 | 1 | HTTP2<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 1529| 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.| 1530 1531## CertType<sup>11+</sup> 1532 1533Enumerates certificate types. 1534 1535**System capability**: SystemCapability.Communication.NetStack 1536 1537| Name| Description | 1538| --- | ---------- | 1539| PEM | PEM certificate.| 1540| DER | DER certificate.| 1541| P12 | P12 certificate.| 1542 1543## CertificatePinning<sup>12+</sup> 1544 1545Defines the dynamic configuration of certificate pinning. 1546 1547**System capability**: SystemCapability.Communication.NetStack 1548 1549| Name | Type | Mandatory |Description | 1550| ------------------ |---- |-- | ----------- | 1551| publicKeyHash | string | Yes|Certificate PIN of the string type.| 1552| hashAlgorithm | 'SHA-256' | Yes |Encryption algorithm. Currently, only SHA-256 is supported.| 1553 1554## HttpProxy<sup>10+</sup> 1555 1556type HttpProxy = connection.HttpProxy 1557 1558Defines the network proxy configuration. 1559 1560**Atomic service API**: This API can be used in atomic services since API version 11. 1561 1562**System capability**: SystemCapability.Communication.NetStack 1563 1564| Type | Description | 1565| ---------------- | --------------------------- | 1566| connection.HttpProxy | Network proxy configuration. | 1567 1568## AddressFamily<sup>15+</sup> 1569 1570Enumerates the address types for domain name resolution. 1571 1572**System capability**: SystemCapability.Communication.NetStack 1573 1574| Name | Description | 1575| ---------------- | --------------------------- | 1576| DEFAULT | Automatically selects the IPv4 or IPv6 address of the target domain name. | 1577| ONLY_V4 | Resolves only the IPv4 address of the target domain name and ignores the IPv6 address. | 1578| ONLY_V6 | Resolves only the IPv6 address of the target domain name and ignores the IPv4 address. | 1579 1580## RemoteValidation<sup>18+</sup> 1581 1582type RemoteValidation = 'system' | 'skip' 1583 1584Certificate authority (CA), which is used to verify the identity of a remote server. You can configure **RemoteValidation** to use the system CA or skip CA verification. 1585 1586**Atomic service API**: This API can be used in atomic services since API version 18. 1587 1588**System capability**: SystemCapability.Communication.NetStack 1589 1590| Type | Description | 1591| ---------------- |---------------| 1592| 'system' | Use of the system CA for verification.| 1593| 'skip' | Skipping of CA verification. | 1594 1595## Credential<sup>18+</sup> 1596 1597Represents the credential used for server identity verification in a session, including the user name and password. 1598 1599**Atomic service API**: This API can be used in atomic services since API version 18. 1600 1601**System capability**: SystemCapability.Communication.NetStack 1602 1603| Name | Type | Read Only | Optional |Description | 1604| ------------------ |---- |-- | -- |----------- | 1605| username | string | No|No|User name used for verification. The default value is **''**.| 1606| password | string | No |No|Password used for verification. The default value is **''**.| 1607 1608## ServerAuthentication<sup>18+</sup> 1609 1610Defines HTTP server identity verification information. 1611 1612**Atomic service API**: This API can be used in atomic services since API version 18. 1613 1614**System capability**: SystemCapability.Communication.NetStack 1615 1616| Name | Type | Read Only | Optional |Description | 1617| ------------------ |-------------------------------------------------|-------- |------------ |---------------| 1618| credential | [Credential](#credential18) | No | No |Server credential. The default value is **undefined**. | 1619| authenticationType | [AuthenticationType](#authenticationtype18) | No | Yes | Server identity verification type. If the type is not set, negotiation with the server is required. | 1620 1621 1622## TlsConfig<sup>18+</sup> 1623 1624Defines the the TLS configuration, including the version and cipher suite. 1625 1626**Atomic service API**: This API can be used in atomic services since API version 18. 1627 1628**System capability**: SystemCapability.Communication.NetStack 1629 1630| Name | Type | Read Only | Optional |Description | 1631| ------------------ |---------------------------------|-------- |-------- |---------------| 1632| tlsVersionMin | [TlsVersion](#tlsversion18) | No |No | Earliest TLS version. | 1633| tlsVersionMax | [TlsVersion](#tlsversion18) | No |No | Latest TLS version. | 1634| cipherSuites | [CipherSuite](#ciphersuite18)[] | No |Yes | Array of cipher suite types.| 1635 1636## TlsVersion<sup>18+</sup> 1637 1638Enumerates TLS versions. 1639 1640**Atomic service API**: This API can be used in atomic services since API version 18. 1641 1642**System capability**: SystemCapability.Communication.NetStack 1643 1644| Name | Value| Description | 1645|:----------|:--|:-----------| 1646| TLS_V_1_0 | 4 | TLS version 1.0.| 1647| TLS_V_1_1 | 5 | TLS version 1.1.| 1648| TLS_V_1_2 | 6 | TLS version 1.2.| 1649| TLS_V_1_3 | 7 | TLS version 1.3.| 1650 1651## TlsOptions<sup>18+</sup> 1652 1653type TlsOptions = 'system' | TlsConfig 1654 1655Defines the TLS configuration. 1656 1657**Atomic service API**: This API can be used in atomic services since API version 18. 1658 1659**System capability**: SystemCapability.Communication.NetStack 1660 1661| Type | Description | 1662|-------------------------------|------------------------------------------------------------------------------------| 1663| 'system' | TLS version of the system. This field is defaulted to **system** when the value is not set.| 1664| TlsOptions | Custom TLS version and cipher suites.| 1665 1666## RemoteValidation<sup>18+</sup> 1667 1668type RemoteValidation = 'system' | 'skip' 1669 1670Enumerates the identity verification modes of the remote server. 1671 1672**Atomic service API**: This API can be used in atomic services since API version 18. 1673 1674**System capability**: SystemCapability.Communication.NetStack 1675 1676| Type | Description | 1677|-------------------------------|------------------------------------------------------------------------------------| 1678| 'system' | Use of the system CA. This field is defaulted to **system** when the value is not set.| 1679| 'skip' | Skipping of CA verification. This field has a fixed value of **skip**.| 1680 1681## AuthenticationType<sup>18+</sup> 1682 1683type AuthenticationType = 'basic' | 'ntlm' | 'digest' 1684 1685Enumerates server authentication modes in a session. 1686 1687**Atomic service API**: This API can be used in atomic services since API version 18. 1688 1689**System capability**: SystemCapability.Communication.NetStack 1690 1691|Type | Description | 1692|-------------------------------|----------------------------------------------------------------------------------------------------| 1693| 'basic' | Basic authentication mode. This field has a fixed value of **basic**.| 1694| 'ntlm' | NTLM authentication mode. This field has a fixed value of **ntlm**.| 1695| 'digest' | Digest authentication mode. This field has a fixed value of **digest**.| 1696 1697## CipherSuite<sup>18+</sup> 1698 1699type CipherSuite = TlsV13CipherSuite 1700 1701Declares the cipher suite. 1702 1703**Atomic service API**: This API can be used in atomic services since API version 18. 1704 1705**System capability**: SystemCapability.Communication.NetStack 1706 1707| Type | Description | 1708| ---------------- |-------------------------------------------------------------------| 1709| TlsV13CipherSuite | Cipher suite defined in [TlsV13CipherSuite](#tlsv13ciphersuite18). | 1710 1711## TlsV13CipherSuite<sup>18+</sup> 1712 1713type TlsV13CipherSuite = TlsV12CipherSuite | TlsV13SpecificCipherSuite 1714 1715Declares the cipher suite for TLS 1.3, which is also compatible with TLS 1.2. 1716 1717**Atomic service API**: This API can be used in atomic services since API version 18. 1718 1719**System capability**: SystemCapability.Communication.NetStack 1720 1721| Type | Description | 1722| ---------------- |-------------------------------------------------------------------| 1723| TlsV12CipherSuite | [TlsV12CipherSuite](#tlsv12ciphersuite18). | 1724| TlsV13SpecificCipherSuite | [TlsV13SpecificCipherSuite](#tlsv13specificciphersuite18).| 1725 1726## TlsV12CipherSuite<sup>18+</sup> 1727 1728type TlsV12CipherSuite = TlsV11CipherSuite | TlsV12SpecificCipherSuite 1729 1730Declares the cipher suite for TLS 1.2, which is also compatible with TLS 1.1. 1731 1732**Atomic service API**: This API can be used in atomic services since API version 18. 1733 1734**System capability**: SystemCapability.Communication.NetStack 1735 1736| Type | Description | 1737| ---------------- |-------------------------------------------------------------------| 1738| TlsV11CipherSuite | [TlsV11CipherSuite](#tlsv11ciphersuite18). | 1739| TlsV12SpecificCipherSuite | [TlsV12SpecificCipherSuite](#tlsv12specificciphersuite18).| 1740 1741## TlsV11CipherSuite<sup>18+</sup> 1742 1743type TlsV11CipherSuite = TlsV10CipherSuite 1744 1745Declares the cipher suite for TLS 1.1, which is the same as that for TLS1.0. 1746 1747**Atomic service API**: This API can be used in atomic services since API version 18. 1748 1749**System capability**: SystemCapability.Communication.NetStack 1750 1751| Type | Description | 1752| ---------------- |---------------------------------------------------| 1753| TlsV10CipherSuite | [TlsV10CipherSuite](#tlsv10ciphersuite18).| 1754 1755## TlsV10CipherSuite<sup>18+</sup> 1756 1757type TlsV10CipherSuite = TlsV10SpecificCipherSuite 1758 1759Declares the cipher suite for TLS 1.0. 1760 1761**Atomic service API**: This API can be used in atomic services since API version 18. 1762 1763**System capability**: SystemCapability.Communication.NetStack 1764 1765| Type | Description | 1766| ---------------- |-------------------------------------------------------------------| 1767| TlsV10SpecificCipherSuite | [TlsV10SpecificCipherSuite](#tlsv10specificciphersuite18).| 1768 1769## TlsV13SpecificCipherSuite<sup>18+</sup> 1770 1771type TlsV13SpecificCipherSuite = 'TLS_AES_128_GCM_SHA256' | 'TLS_AES_256_GCM_SHA384' | 'TLS_CHACHA20_POLY1305_SHA256' 1772 1773Enumerates cipher suites supported by TLS 1.3 or later. 1774 1775**Atomic service API**: This API can be used in atomic services since API version 18. 1776 1777**System capability**: SystemCapability.Communication.NetStack 1778 1779| Type | Description | 1780| ---------------- |------| 1781| 'TLS_AES_128_GCM_SHA256' | Supported cipher suite: TLS_AES_128_GCM_SHA256. The value is a string.| 1782| 'TLS_AES_256_GCM_SHA384' | Supported cipher suite: TLS_AES_256_GCM_SHA384. The value is a string.| 1783| 'TLS_CHACHA20_POLY1305_SHA256' | Supported cipher suite: TLS_CHACHA20_POLY1305_SHA256. The value is a string.| 1784 1785## TlsV12SpecificCipherSuite<sup>18+</sup> 1786 1787type TlsV12SpecificCipherSuite = 'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256' | 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256' | 1788'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384' | 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384' | 1789'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256' | 'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256' | 1790'TLS_RSA_WITH_AES_128_GCM_SHA256' | 'TLS_RSA_WITH_AES_256_GCM_SHA384' 1791 1792Enumerates cipher suites supported by TLS 1.2 or later. 1793 1794**Atomic service API**: This API can be used in atomic services since API version 18. 1795 1796**System capability**: SystemCapability.Communication.NetStack 1797 1798| Type | Description | 1799| ---------------- |------| 1800| 'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256' | Supported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256. The value is a string.| 1801| 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256' | Supported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256. The value is a string.| 1802| 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384' | Supported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384. The value is a string.| 1803| 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384' | Supported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384. The value is a string.| 1804| 'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256' | Supported cipher suite: TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256. The value is a string.| 1805| 'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256' | Supported cipher suite: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256. The value is a string.| 1806| 'TLS_RSA_WITH_AES_128_GCM_SHA256' | Supported cipher suite: TLS_RSA_WITH_AES_128_GCM_SHA256. The value is a string.| 1807| 'TLS_RSA_WITH_AES_256_GCM_SHA384' | Supported cipher suite: TLS_RSA_WITH_AES_256_GCM_SHA384. The value is a string.| 1808 1809## TlsV10SpecificCipherSuite<sup>18+</sup> 1810 1811type TlsV10SpecificCipherSuite = 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA' | 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA' | 1812'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA' | 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA' | 'TLS_RSA_WITH_AES_128_CBC_SHA' | 1813'TLS_RSA_WITH_AES_256_CBC_SHA' | 'TLS_RSA_WITH_3DES_EDE_CBC_SHA' 1814 1815Enumerates cipher suites supported by TLS 1.0 or later. 1816 1817**Atomic service API**: This API can be used in atomic services since API version 18. 1818 1819**System capability**: SystemCapability.Communication.NetStack 1820 1821| Type | Description | 1822| ---------------- |------| 1823| 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA' | Supported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA. The value is a string.| 1824| 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA' | Supported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA. The value is a string.| 1825| 'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA' | Supported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA. The value is a string.| 1826| 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA' | Supported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA. The value is a string.| 1827| 'TLS_RSA_WITH_AES_128_CBC_SHA' | Supported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA. The value is a string.| 1828| 'TLS_RSA_WITH_AES_256_CBC_SHA' | Supported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA. The value is a string.| 1829| 'TLS_RSA_WITH_3DES_EDE_CBC_SHA' | Supported cipher suite: TLS_RSA_WITH_3DES_EDE_CBC_SHA. The value is a string.| 1830