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**Atomic service API**: This API can be used in atomic services since API version 15. 461 462**System capability**: SystemCapability.Communication.NetStack 463 464**Parameters** 465 466| Name | Type | Mandatory| Description | 467| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 468| url | string | Yes | URL for initiating an HTTP request. | 469| callback | AsyncCallback\<number\> | Yes | Callback used to return the result. | 470 471**Error codes** 472 473| ID | Error Message | 474|---------|----------------------------------------------------------------| 475| 401 | Parameter error. | 476| 201 | Permission denied. | 477| 2300001 | Unsupported protocol. | 478| 2300003 | Invalid URL format or missing URL. | 479| 2300005 | Failed to resolve the proxy name. | 480| 2300006 | Failed to resolve the host name. | 481| 2300007 | Failed to connect to the server. | 482| 2300008 | Invalid server response. | 483| 2300009 | Access to the remote resource denied. | 484| 2300016 | Error in the HTTP2 framing layer. | 485| 2300018 | Transferred a partial file. | 486| 2300023 | Failed to write the received data to the disk or application. | 487| 2300025 | Upload failed. | 488| 2300026 | Failed to open or read local data from the file or application.| 489| 2300027 | Out of memory. | 490| 2300028 | Operation timeout. | 491| 2300047 | The number of redirections reaches the maximum allowed. | 492| 2300052 | The server returned nothing (no header or data). | 493| 2300055 | Failed to send data to the peer. | 494| 2300056 | Failed to receive data from the peer. | 495| 2300058 | Local SSL certificate error. | 496| 2300059 | The specified SSL cipher cannot be used. | 497| 2300060 | Invalid SSL peer certificate or SSH remote key. | 498| 2300061 | Invalid HTTP encoding format. | 499| 2300063 | Maximum file size exceeded. | 500| 2300070 | Remote disk full. | 501| 2300073 | Remote file already exists. | 502| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 503| 2300078 | Remote file not found. | 504| 2300094 | Authentication error. | 505| 2300997 | Cleartext traffic not permitted. | 506| 2300998 | It is not allowed to access this domain. | 507| 2300999 | Unknown error. | 508 509> **NOTE** 510> For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [HTTP Error Codes](errorcode-net-http.md). 511> 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). 512 513**Example** 514 515```ts 516import { http } from '@kit.NetworkKit'; 517import { BusinessError } from '@kit.BasicServicesKit'; 518 519let httpRequest = http.createHttp(); 520httpRequest.requestInStream("EXAMPLE_URL", (err: BusinessError, data: number) => { 521 if (!err) { 522 console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); 523 } else { 524 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 525 } 526}) 527``` 528 529### requestInStream<sup>10+</sup> 530 531requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void 532 533Initiates 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. 534 535**Required permissions**: ohos.permission.INTERNET 536 537**Atomic service API**: This API can be used in atomic services since API version 15. 538 539**System capability**: SystemCapability.Communication.NetStack 540 541**Parameters** 542 543| Name | Type | Mandatory| Description | 544| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 545| url | string | Yes | URL for initiating an HTTP request. | 546| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 547| callback | AsyncCallback\<[number](#responsecode)\> | Yes | Callback used to return the result. | 548 549**Error codes** 550 551| ID | Error Message | 552|---------|----------------------------------------------------------------| 553| 401 | Parameter error. | 554| 201 | Permission denied. | 555| 2300001 | Unsupported protocol. | 556| 2300003 | Invalid URL format or missing URL. | 557| 2300005 | Failed to resolve the proxy name. | 558| 2300006 | Failed to resolve the host name. | 559| 2300007 | Failed to connect to the server. | 560| 2300008 | Invalid server response. | 561| 2300009 | Access to the remote resource denied. | 562| 2300016 | Error in the HTTP2 framing layer. | 563| 2300018 | Transferred a partial file. | 564| 2300023 | Failed to write the received data to the disk or application. | 565| 2300025 | Upload failed. | 566| 2300026 | Failed to open or read local data from the file or application.| 567| 2300027 | Out of memory. | 568| 2300028 | Operation timeout. | 569| 2300047 | The number of redirections reaches the maximum allowed. | 570| 2300052 | The server returned nothing (no header or data). | 571| 2300055 | Failed to send data to the peer. | 572| 2300056 | Failed to receive data from the peer. | 573| 2300058 | Local SSL certificate error. | 574| 2300059 | The specified SSL cipher cannot be used. | 575| 2300060 | Invalid SSL peer certificate or SSH remote key. | 576| 2300061 | Invalid HTTP encoding format. | 577| 2300063 | Maximum file size exceeded. | 578| 2300070 | Remote disk full. | 579| 2300073 | Remote file already exists. | 580| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 581| 2300078 | Remote file not found. | 582| 2300094 | Authentication error. | 583| 2300997 | Cleartext traffic not permitted. | 584| 2300998 | It is not allowed to access this domain. | 585| 2300999 | Unknown error. | 586 587> **NOTE** 588> For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [HTTP Error Codes](errorcode-net-http.md). 589> 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). 590 591**Example** 592 593```ts 594import { http } from '@kit.NetworkKit'; 595import { BusinessError } from '@kit.BasicServicesKit'; 596 597class Header { 598 public contentType: string; 599 600 constructor(contentType: string) { 601 this.contentType = contentType; 602 } 603} 604 605let httpRequest = http.createHttp(); 606let options: http.HttpRequestOptions = { 607 method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. 608 // This field is used to transfer the request body when a POST request is used. Its format needs to be negotiated with the server. 609 extraData: 'data to send', 610 expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data. 611 usingCache: true, // Optional. The default value is true. 612 priority: 1, // Optional. The default value is 1. 613 // You can add header fields based on service requirements. 614 header: new Header('application/json'), 615 readTimeout: 60000, // Optional. The default value is 60000, in ms. 616 connectTimeout: 60000 // Optional. The default value is 60000, in ms. 617 usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. 618 usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API version 10. 619}; 620httpRequest.requestInStream("EXAMPLE_URL", options, (err: BusinessError<void> , data: number) => { 621 if (!err) { 622 console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); 623 } else { 624 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 625 } 626}) 627``` 628 629### requestInStream<sup>10+</sup> 630 631requestInStream(url: string, options? : HttpRequestOptions): Promise\<number\> 632 633Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response. 634 635**Required permissions**: ohos.permission.INTERNET 636 637**Atomic service API**: This API can be used in atomic services since API version 15. 638 639**System capability**: SystemCapability.Communication.NetStack 640 641**Parameters** 642 643| Name | Type | Mandatory| Description | 644| ------- | ------------------ | ---- | ----------------------------------------------- | 645| url | string | Yes | URL for initiating an HTTP request. | 646| options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 647 648**Return value** 649 650| Type | Description | 651| :------------------------------------- | :-------------------------------- | 652| Promise\<[number](#responsecode)\> | Promise used to return the result.| 653 654**Error codes** 655 656| ID | Error Message | 657|---------|----------------------------------------------------------------| 658| 401 | Parameter error. | 659| 201 | Permission denied. | 660| 2300001 | Unsupported protocol. | 661| 2300003 | Invalid URL format or missing URL. | 662| 2300005 | Failed to resolve the proxy name. | 663| 2300006 | Failed to resolve the host name. | 664| 2300007 | Failed to connect to the server. | 665| 2300008 | Invalid server response. | 666| 2300009 | Access to the remote resource denied. | 667| 2300016 | Error in the HTTP2 framing layer. | 668| 2300018 | Transferred a partial file. | 669| 2300023 | Failed to write the received data to the disk or application. | 670| 2300025 | Upload failed. | 671| 2300026 | Failed to open or read local data from the file or application.| 672| 2300027 | Out of memory. | 673| 2300028 | Operation timeout. | 674| 2300047 | The number of redirections reaches the maximum allowed. | 675| 2300052 | The server returned nothing (no header or data). | 676| 2300055 | Failed to send data to the peer. | 677| 2300056 | Failed to receive data from the peer. | 678| 2300058 | Local SSL certificate error. | 679| 2300059 | The specified SSL cipher cannot be used. | 680| 2300060 | Invalid SSL peer certificate or SSH remote key. | 681| 2300061 | Invalid HTTP encoding format. | 682| 2300063 | Maximum file size exceeded. | 683| 2300070 | Remote disk full. | 684| 2300073 | Remote file already exists. | 685| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 686| 2300078 | Remote file not found. | 687| 2300094 | Authentication error. | 688| 2300997 | Cleartext traffic not permitted. | 689| 2300998 | It is not allowed to access this domain. | 690| 2300999 | Unknown error. | 691 692> **NOTE** 693> For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [HTTP Error Codes](errorcode-net-http.md). 694> 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). 695 696**Example** 697 698```ts 699import { http } from '@kit.NetworkKit'; 700 701class Header { 702 public contentType: string; 703 704 constructor(contentType: string) { 705 this.contentType = contentType; 706 } 707} 708 709let httpRequest = http.createHttp(); 710let promise = httpRequest.requestInStream("EXAMPLE_URL", { 711 method: http.RequestMethod.GET, 712 connectTimeout: 60000, 713 readTimeout: 60000, 714 header: new Header('application/json') 715}); 716promise.then((data: number) => { 717 console.info("requestInStream OK!" + data); 718}).catch((err: Error) => { 719 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 720}); 721``` 722 723### on("headerReceive")<sup>(deprecated)</sup> 724 725on(type: "headerReceive", callback: AsyncCallback\<Object\>): void 726 727Registers an observer for HTTP Response Header events. 728 729> **NOTE** 730> This API has been deprecated. You are advised to use [on("headersReceive")<sup>8+</sup>](#onheadersreceive8). 731 732**System capability**: SystemCapability.Communication.NetStack 733 734**Parameters** 735 736| Name | Type | Mandatory| Description | 737| -------- | ----------------------- | ---- | --------------------------------- | 738| type | string | Yes | Event type. The value is **headerReceive**.| 739| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. | 740 741**Example** 742 743```ts 744import { http } from '@kit.NetworkKit'; 745import { BusinessError } from '@kit.BasicServicesKit'; 746 747let httpRequest = http.createHttp(); 748httpRequest.on("headerReceive", (data: BusinessError) => { 749 console.info("error:" + JSON.stringify(data)); 750}); 751``` 752 753### off("headerReceive")<sup>(deprecated)</sup> 754 755off(type: "headerReceive", callback?: AsyncCallback\<Object\>): void 756 757Unregisters the observer for HTTP Response Header events. 758 759> **NOTE** 760> 761>- This API has been deprecated. You are advised to use [off("headersReceive")<sup>8+</sup>](#offheadersreceive8). 762> 763>- 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. 764 765**System capability**: SystemCapability.Communication.NetStack 766 767**Parameters** 768 769| Name | Type | Mandatory| Description | 770| -------- | ----------------------- | ---- | ------------------------------------- | 771| type | string | Yes | Event type. The value is **headerReceive**.| 772| callback | AsyncCallback\<Object\> | No | Callback used to return the result. | 773 774**Example** 775 776```ts 777import { http } from '@kit.NetworkKit'; 778 779let httpRequest = http.createHttp(); 780httpRequest.off("headerReceive"); 781``` 782 783### on("headersReceive")<sup>8+</sup> 784 785on(type: "headersReceive", callback: Callback\<Object\>): void 786 787Registers an observer for HTTP Response Header events. 788 789**Atomic service API**: This API can be used in atomic services since API version 11. 790 791**System capability**: SystemCapability.Communication.NetStack 792 793**Parameters** 794 795| Name | Type | Mandatory| Description | 796| -------- | ------------------ | ---- | ---------------------------------- | 797| type | string | Yes | Event type. The value is **headersReceive**.| 798| callback | Callback\<Object\> | Yes | Callback used to return the result. | 799 800**Example** 801 802```ts 803import { http } from '@kit.NetworkKit'; 804 805let httpRequest = http.createHttp(); 806httpRequest.on("headersReceive", (header: Object) => { 807 console.info("header: " + JSON.stringify(header)); 808}); 809httpRequest.off("headersReceive"); 810``` 811 812### off("headersReceive")<sup>8+</sup> 813 814off(type: "headersReceive", callback?: Callback\<Object\>): void 815 816Unregisters the observer for HTTP Response Header events. 817 818> **NOTE** 819> 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. 820 821**Atomic service API**: This API can be used in atomic services since API version 11. 822 823**System capability**: SystemCapability.Communication.NetStack 824 825**Parameters** 826 827| Name | Type | Mandatory| Description | 828| -------- | ------------------ | ---- | -------------------------------------- | 829| type | string | Yes | Event type. The value is **headersReceive**.| 830| callback | Callback\<Object\> | No | Callback used to return the result. | 831 832**Example** 833 834```ts 835import { http } from '@kit.NetworkKit'; 836 837let httpRequest = http.createHttp(); 838httpRequest.on("headersReceive", (header: Object) => { 839 console.info("header: " + JSON.stringify(header)); 840}); 841httpRequest.off("headersReceive"); 842``` 843 844### once("headersReceive")<sup>8+</sup> 845 846once(type: "headersReceive", callback: Callback\<Object\>): void 847 848Registers 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. 849 850**Atomic service API**: This API can be used in atomic services since API version 15. 851 852**System capability**: SystemCapability.Communication.NetStack 853 854**Parameters** 855 856| Name | Type | Mandatory| Description | 857| -------- | ------------------ | ---- | ---------------------------------- | 858| type | string | Yes | Event type. The value is **headersReceive**.| 859| callback | Callback\<Object\> | Yes | Callback used to return the result. | 860 861**Example** 862 863```ts 864import { http } from '@kit.NetworkKit'; 865 866let httpRequest = http.createHttp(); 867httpRequest.once("headersReceive", (header: Object) => { 868 console.info("header: " + JSON.stringify(header)); 869}); 870``` 871 872### on("dataReceive")<sup>10+</sup> 873 874on(type: "dataReceive", callback: Callback\<ArrayBuffer\>): void 875 876Registers an observer for events indicating receiving of HTTP streaming responses. 877 878**Atomic service API**: This API can be used in atomic services since API version 15. 879 880**System capability**: SystemCapability.Communication.NetStack 881 882**Parameters** 883 884| Name | Type | Mandatory| Description | 885| -------- | ----------------------- | ---- | --------------------------------- | 886| type | string | Yes | Event type. The value is **dataReceive**.| 887| callback | AsyncCallback\<ArrayBuffer\> | Yes | Callback used to return the result. | 888 889**Example** 890 891```ts 892import { http } from '@kit.NetworkKit'; 893 894let httpRequest = http.createHttp(); 895httpRequest.on("dataReceive", (data: ArrayBuffer) => { 896 console.info("dataReceive length: " + JSON.stringify(data.byteLength)); 897}); 898httpRequest.off("dataReceive"); 899``` 900 901### off("dataReceive")<sup>10+</sup> 902 903off(type: "dataReceive", callback?: Callback\<ArrayBuffer\>): void 904 905Unregisters the observer for events indicating receiving of HTTP streaming responses. 906 907> **NOTE** 908> 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. 909 910**Atomic service API**: This API can be used in atomic services since API version 15. 911 912**System capability**: SystemCapability.Communication.NetStack 913 914**Parameters** 915 916| Name | Type | Mandatory| Description | 917| -------- | ------------------ | ---- | -------------------------------------- | 918| type | string | Yes | Event type. The value is **dataReceive**.| 919| callback | Callback\<ArrayBuffer\> | No | Callback used to return the result. | 920 921**Example** 922 923```ts 924import { http } from '@kit.NetworkKit'; 925 926let httpRequest = http.createHttp(); 927httpRequest.on("dataReceive", (data: ArrayBuffer) => { 928 console.info("dataReceive length: " + JSON.stringify(data.byteLength)); 929}); 930httpRequest.off("dataReceive"); 931``` 932 933### on("dataEnd")<sup>10+</sup> 934 935on(type: "dataEnd", callback: Callback\<void\>): void 936 937Registers an observer for events indicating completion of receiving HTTP streaming responses. 938 939**Atomic service API**: This API can be used in atomic services since API version 15. 940 941**System capability**: SystemCapability.Communication.NetStack 942 943**Parameters** 944 945| Name | Type | Mandatory| Description | 946| -------- | ----------------------- | ---- | --------------------------------- | 947| type | string | Yes | Event type. The value is **dataEnd**.| 948| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 949 950**Example** 951 952```ts 953import { http } from '@kit.NetworkKit'; 954 955let httpRequest = http.createHttp(); 956httpRequest.on("dataEnd", () => { 957 console.info("Receive dataEnd !"); 958}); 959httpRequest.off("dataEnd"); 960``` 961 962### off("dataEnd")<sup>10+</sup> 963 964off(type: "dataEnd", callback?: Callback\<void\>): void 965 966Unregisters the observer for events indicating completion of receiving HTTP streaming responses. 967 968> **NOTE** 969> 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. 970 971**Atomic service API**: This API can be used in atomic services since API version 15. 972 973**System capability**: SystemCapability.Communication.NetStack 974 975**Parameters** 976 977| Name | Type | Mandatory| Description | 978| -------- | ------------------ | ---- | -------------------------------------- | 979| type | string | Yes | Event type. The value is **dataEnd**.| 980| callback | Callback\<void\> | No | Callback used to return the result. | 981 982**Example** 983 984```ts 985import { http } from '@kit.NetworkKit'; 986 987let httpRequest = http.createHttp(); 988httpRequest.on("dataEnd", () => { 989 console.info("Receive dataEnd !"); 990}); 991httpRequest.off("dataEnd"); 992``` 993 994### on('dataReceiveProgress')<sup>10+</sup> 995 996on(type: 'dataReceiveProgress', callback: Callback\<DataReceiveProgressInfo\>): void 997 998Registers an observer for events indicating progress of receiving HTTP streaming responses. 999 1000**Atomic service API**: This API can be used in atomic services since API version 15. 1001 1002**System capability**: SystemCapability.Communication.NetStack 1003 1004**Parameters** 1005 1006| Name | Type | Mandatory| Description | 1007| -------- | ----------------------- | ---- | --------------------------------- | 1008| type | string | Yes | Event type. The value is **dataReceiveProgress**.| 1009| callback | AsyncCallback\<[DataReceiveProgressInfo](#datareceiveprogressinfo11)\> | Yes | Callback used to return the result. | 1010 1011**Example** 1012 1013```ts 1014import { http } from '@kit.NetworkKit'; 1015 1016let httpRequest = http.createHttp(); 1017httpRequest.on("dataReceiveProgress", (data: http.DataReceiveProgressInfo) => { 1018 console.info("dataReceiveProgress:" + JSON.stringify(data)); 1019}); 1020httpRequest.off("dataReceiveProgress"); 1021``` 1022 1023### off('dataReceiveProgress')<sup>10+</sup> 1024 1025off(type: 'dataReceiveProgress', callback?: Callback\<DataReceiveProgressInfo\>): void 1026 1027Unregisters the observer for events indicating progress of receiving HTTP streaming responses. 1028 1029> **NOTE** 1030> 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. 1031 1032**Atomic service API**: This API can be used in atomic services since API version 15. 1033 1034**System capability**: SystemCapability.Communication.NetStack 1035 1036**Parameters** 1037 1038| Name | Type | Mandatory| Description | 1039| -------- | ------------------ | ---- | -------------------------------------- | 1040| type | string | Yes | Event type. The value is **dataReceiveProgress**.| 1041| callback | Callback\<[DataReceiveProgressInfo](#datareceiveprogressinfo11)\> | No | Callback used to return the result. | 1042 1043**Example** 1044 1045```ts 1046import { http } from '@kit.NetworkKit'; 1047 1048let httpRequest = http.createHttp(); 1049httpRequest.on("dataReceiveProgress", (data: http.DataReceiveProgressInfo) => { 1050 console.info("dataReceiveProgress:" + JSON.stringify(data)); 1051}); 1052httpRequest.off("dataReceiveProgress"); 1053``` 1054 1055### on('dataSendProgress')<sup>11+</sup> 1056 1057on(type: 'dataSendProgress', callback: Callback\<DataSendProgressInfo\>): void 1058 1059Registers an observer for events indicating progress of sending HTTP requests. 1060 1061**Atomic service API**: This API can be used in atomic services since API version 15. 1062 1063**System capability**: SystemCapability.Communication.NetStack 1064 1065**Parameters** 1066 1067| Name | Type | Mandatory| Description | 1068| -------- | ----------------------- | ---- | --------------------------------- | 1069| type | string | Yes | Event type. The value is **dataSendProgress**.| 1070| callback | AsyncCallback\<[DataSendProgressInfo](#datasendprogressinfo11)\> | Yes | Callback used to return the result. | 1071 1072**Example** 1073 1074```ts 1075import { http } from '@kit.NetworkKit'; 1076 1077let httpRequest = http.createHttp(); 1078httpRequest.on("dataSendProgress", (data: http.DataSendProgressInfo) => { 1079 console.info("dataSendProgress:" + JSON.stringify(data)); 1080}); 1081httpRequest.off("dataSendProgress"); 1082``` 1083 1084### off('dataSendProgress')<sup>11+</sup> 1085 1086off(type: 'dataSendProgress', callback?: Callback\<DataSendProgressInfo\>): void 1087 1088Unregisters the observer for events indicating progress of sending HTTP requests. 1089 1090> **NOTE** 1091> 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. 1092 1093**Atomic service API**: This API can be used in atomic services since API version 15. 1094 1095**System capability**: SystemCapability.Communication.NetStack 1096 1097**Parameters** 1098 1099| Name | Type | Mandatory| Description | 1100| -------- | ------------------ | ---- | -------------------------------------- | 1101| type | string | Yes | Event type. The value is **dataSendProgress**.| 1102| callback | Callback\<[DataSendProgressInfo](#datasendprogressinfo11)\> | No| Callback used to return the result. | 1103 1104**Example** 1105 1106```ts 1107import { http } from '@kit.NetworkKit'; 1108 1109let httpRequest = http.createHttp(); 1110httpRequest.on("dataSendProgress", (data: http.DataSendProgressInfo) => { 1111 console.info("dataSendProgress:" + JSON.stringify(data)); 1112}); 1113httpRequest.off("dataSendProgress"); 1114``` 1115 1116## HttpRequestOptions 1117 1118Specifies the type and value range of the optional parameters in the HTTP request. 1119 1120**System capability**: SystemCapability.Communication.NetStack 1121 1122| Name | Type | Mandatory| Description | 1123| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 1124| 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. | 1125| 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.| 1126| 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.| 1127| 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 value **true** means to use the cache to replace the old one, and the value **false** means not to use the cache.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 1128| 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. | 1129| 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. | 1130| 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.| 1131| 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. | 1132| 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. | 1133| usingProxy<sup>10+</sup> | boolean \| [HttpProxy](js-apis-net-connection.md#httpproxy10) | No | Whether to use the HTTP proxy. The value **true** means to use the HTTP proxy, and the value **false** means the opposite. The default value is **false**.<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.| 1134| 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. | 1135| 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.| 1136| 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.| 1137| clientCert<sup>11+</sup> | [ClientCert](#clientcert11) | No| Client certificate.| 1138| 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".| 1139| 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.| 1140| 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**. | 1141| multiFormDataList<sup>11+</sup> | Array<[MultiFormData](#multiformdata11)> | No| Form data list. This field is valid when **content-Type** is set to **multipart/form-data**.| 1142| certificatePinning<sup>12+</sup> | [CertificatePinning](#certificatepinning12) \| CertificatePinning[] | No| Dynamic configuration of certificate pinning. One or more certificate PINs can be specified.| 1143| addressFamily<sup>15+</sup> | [AddressFamily](#addressfamily15) | No| IP address family. You can specify an address type for domain name resolution.| 1144| 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. | 1145| 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. | 1146| 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. | 1147 1148## RequestMethod 1149 1150Defines an HTTP request method. 1151 1152**Atomic service API**: This API can be used in atomic services since API version 11. 1153 1154**System capability**: SystemCapability.Communication.NetStack 1155 1156| Name | Value | Description | 1157| :------ | ------- | :------------------ | 1158| OPTIONS | "OPTIONS" | Describes the communication options of the target resource.| 1159| GET | "GET" | Requests the representation of the specified resource. The GET request should only retrieve data and should not contain the request content.| 1160| HEAD | "HEAD" | Requests the same response (but does not have a response body) as the GET request.| 1161| POST | "POST" | Submits an entity to a specified resource, which usually causes a status change on the server.| 1162| PUT | "PUT" | Replaces all current representations of the target resource with the requested content.| 1163| DELETE | "DELETE" | Deletes the specified resource.| 1164| TRACE | "TRACE" | Performs a message loopback test along the path to the target resource.| 1165| CONNECT | "CONNECT" | Establishes a tunnel to the server identified by the target resource.| 1166 1167## ResponseCode 1168 1169Enumerates the response codes for an HTTP request. 1170 1171**System capability**: SystemCapability.Communication.NetStack 1172 1173| Name | Value | Description | 1174| ----------------- | ---- | ------------------------------------------------------------ | 1175| 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. | 1176| 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. | 1177| 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. | 1178| 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. | 1179| 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. | 1180| 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. | 1181| 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. | 1182| 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. | 1183| 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.| 1184| 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. | 1185| 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. | 1186| 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. | 1187| 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. | 1188| 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. | 1189| UNAUTHORIZED | 401 | "Unauthorized." The request requires user authentication.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 1190| 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. | 1191| 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. | 1192| 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. | 1193| 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. | 1194| 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. | 1195| 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. | 1196| 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. | 1197| 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.| 1198| 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. | 1199| 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. | 1200| 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. | 1201| 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. | 1202| 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. | 1203| 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. | 1204| 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. | 1205| 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. | 1206| 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. | 1207| 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.| 1208| 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. | 1209| 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. | 1210| 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. | 1211 1212## HttpResponse 1213 1214Defines the response to an HTTP request. 1215 1216**System capability**: SystemCapability.Communication.NetStack 1217 1218| Name | Type | Mandatory| Description | 1219| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 1220| 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.| 1221| 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. | 1222| 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.| 1223| 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.| 1224| 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. | 1225| performanceTiming<sup>11+</sup> | [PerformanceTiming](#performancetiming11) | Yes| Time consumed in each phase of an HTTP request.| 1226 1227## ClientCert<sup>11+</sup> 1228 1229Defines the client certificate type. 1230 1231**System capability**: SystemCapability.Communication.NetStack 1232 1233| Name| Type| Mandatory| Description| 1234| -------- | -------| --- | ----------- | 1235| certPath | string | Yes| Path of the certificate file.| 1236| certType | [CertType](#certtype11) | No| Certificate type. The default value is **PEM**.| 1237| keyPath | string | Yes| Path of the certificate key file.| 1238| keyPassword | string | No | Password of the certificate key file.| 1239 1240## PerformanceTiming<sup>11+</sup> 1241 1242Configures the timing for performance tracing, in ms. 1243 1244**System capability**: SystemCapability.Communication.NetStack 1245 1246| Name | Type | Mandatory | Description | 1247| ---------- | ------ | ---- | --------------------- | 1248| dnsTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the DNS resolution is complete.| 1249| tcpTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the TCP connection is complete.| 1250| tlsTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the TLS connection is complete.| 1251| firstSendTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the first byte is sent.| 1252| firstReceiveTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the first byte is received.| 1253| totalFinishTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the request is complete.| 1254| redirectTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when all redirection steps are complete.| 1255| responseHeaderTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the header resolution is complete.| 1256| responseBodyTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when the body resolution is complete.| 1257| totalTiming | number | Yes | Duration from the time when the [request](#request) is sent to the time when a callback is returned to the application.| 1258 1259## DataReceiveProgressInfo<sup>11+</sup> 1260 1261Defines the data receiving progress information. 1262 1263**Atomic service API**: This API can be used in atomic services since API version 15. 1264 1265**System capability**: SystemCapability.Communication.NetStack 1266 1267| Name| Type| Mandatory| Description| 1268| ---- | ---- | ---- | ---- | 1269| receiveSize | number | Yes | Size of data that has been received, in bytes.<br>**Atomic service API**: This API can be used in atomic services since API version 15. | 1270| totalSize| number | Yes| Total size of data to be received, in bytes.<br>**Atomic service API**: This API can be used in atomic services since API version 15.| 1271 1272## DataSendProgressInfo<sup>11+</sup> 1273 1274Defines the data sending progress information. 1275 1276**Atomic service API**: This API can be used in atomic services since API version 15. 1277 1278**System capability**: SystemCapability.Communication.NetStack 1279 1280### Attributes 1281 1282| Name| Type| Mandatory| Description| 1283| ---- | ---- | ---- | ---- | 1284| sendSize | number | Yes | Size of data to be sent, in bytes. | 1285| totalSize | number | Yes| Total size of data to be sent, in bytes.| 1286 1287## MultiFormData<sup>11+</sup> 1288 1289Defines the type of multi-form data. 1290 1291**System capability**: SystemCapability.Communication.NetStack 1292 1293| Name| Type| Mandatory| Description| 1294| ---- | ---- | ---- | ---- | 1295| name | string | Yes | Data name. | 1296| contentType | string | Yes| Data type, for example, **text/plain**, **image/png**, **image/jpeg**, **audio/mpeg**, or **video/mp4**.| 1297| remoteFileName | string | No| Name of the file uploaded to the server. | 1298| data | string \| Object \| ArrayBuffer | No| Form data content. | 1299| 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.| 1300 1301## http.createHttpResponseCache<sup>9+</sup> 1302 1303createHttpResponseCache(cacheSize?: number): HttpResponseCache 1304 1305Creates 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. 1306 1307**Atomic service API**: This API can be used in atomic services since API version 11. 1308 1309**System capability**: SystemCapability.Communication.NetStack 1310 1311**Parameters** 1312 1313| Name | Type | Mandatory| Description | 1314| -------- | --------------------------------------- | ---- | ---------- | 1315| cacheSize | number | No| Cache size. The maximum value is 10\*1024\*1024 (10 MB). By default, the maximum value is used.| 1316 1317**Return value** 1318 1319| Type | Description | 1320| :---------- | :----------------------------------------------------------- | 1321| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.| 1322 1323**Example** 1324 1325```ts 1326import { http } from '@kit.NetworkKit'; 1327 1328let httpResponseCache = http.createHttpResponseCache(); 1329``` 1330 1331## HttpResponseCache<sup>9+</sup> 1332 1333Defines 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. 1334 1335**Usage of Keywords in the Response Header** 1336 1337- **`Cache-Control`**: specifies the cache policy, for example, `no-cache`, `no-store`, `max-age`, `public`, or `private`. 1338 1339- **`Expires`**: specifies the expiration time of a resource. The value is in the GMT format. 1340 1341- **`ETag`**: identifies the resource version. The client can use the `If-None-Match` request header to check whether the resource has been modified. 1342 1343- **`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. 1344 1345- **`Vary`**: specifies the parts of the request header that affect the cached response. This field is used to distinguish different cache versions. 1346 1347When 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. 1348 1349**How to Set the Cache-Control Header** 1350 1351`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: 1352 1353- **`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. 1354 1355- `no-store`: indicates that resources cannot be cached. Resources must be obtained from the server for each request. 1356 1357- `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). 1358 1359- `public`: indicates that the response can be cached by any object, for example, the client that sends the request or the proxy server. 1360 1361- `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). 1362 1363- `must-revalidate`: indicates that a resource must be revalidated with the origin server once it has become stable. 1364 1365- **`no-transform`**: indicates that the proxy server is not allowed to modify the response content. 1366 1367- **`proxy-revalidate`**: works in a way similar to `must-revalidate`, but applies only to shared caches. 1368 1369- **`s-maxage`**: works in a way similar to `max-age`, but applies only to shared caches. 1370 1371### flush<sup>9+</sup> 1372 1373flush(callback: AsyncCallback\<void\>): void 1374 1375Flushes 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). 1376 1377**Atomic service API**: This API can be used in atomic services since API version 11. 1378 1379**System capability**: SystemCapability.Communication.NetStack 1380 1381**Parameters** 1382 1383| Name | Type | Mandatory| Description | 1384| -------- | --------------------------------------- | ---- | ---------- | 1385| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 1386 1387**Example** 1388 1389```ts 1390import { http } from '@kit.NetworkKit'; 1391import { BusinessError } from '@kit.BasicServicesKit'; 1392 1393let httpResponseCache = http.createHttpResponseCache(); 1394let httpRequest = http.createHttp(); 1395httpRequest.request("EXAMPLE_URL", (err: BusinessError, data: http.HttpResponse) => { 1396 if (!err) { 1397 httpResponseCache.flush((err: BusinessError) => { 1398 if (err) { 1399 console.error('flush fail'); 1400 } 1401 console.info('flush success'); 1402 }); 1403 httpRequest.destroy(); 1404 } else { 1405 console.error('error:' + JSON.stringify(err)); 1406 // Call destroy() to destroy the JavaScript object after the HTTP request is complete. 1407 httpRequest.destroy(); 1408 } 1409}); 1410``` 1411 1412### flush<sup>9+</sup> 1413 1414flush(): Promise\<void\> 1415 1416Flushes 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. 1417 1418**Atomic service API**: This API can be used in atomic services since API version 11. 1419 1420**System capability**: SystemCapability.Communication.NetStack 1421 1422**Return value** 1423 1424| Type | Description | 1425| --------------------------------- | ------------------------------------- | 1426| Promise\<void\> | Promise used to return the result.| 1427 1428**Example** 1429 1430```ts 1431import { http } from '@kit.NetworkKit'; 1432import { BusinessError } from '@kit.BasicServicesKit'; 1433 1434let httpRequest = http.createHttp(); 1435let httpResponseCache = http.createHttpResponseCache(); 1436let promise = httpRequest.request("EXAMPLE_URL"); 1437 1438promise.then((data: http.HttpResponse) => { 1439 httpResponseCache.flush().then(() => { 1440 console.error('flush success'); 1441 }).catch((err: BusinessError) => { 1442 console.info('flush fail'); 1443 }); 1444}).catch((err: Error) => { 1445 console.error('error:' + JSON.stringify(err)); 1446}); 1447``` 1448 1449### delete<sup>9+</sup> 1450 1451delete(callback: AsyncCallback\<void\>): void 1452 1453Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result. 1454 1455**Atomic service API**: This API can be used in atomic services since API version 11. 1456 1457**System capability**: SystemCapability.Communication.NetStack 1458 1459**Parameters** 1460 1461| Name | Type | Mandatory| Description | 1462| -------- | --------------------------------------- | ---- | ---------- | 1463| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 1464 1465**Example** 1466 1467```ts 1468import { http } from '@kit.NetworkKit'; 1469import { BusinessError } from '@kit.BasicServicesKit'; 1470 1471let httpRequest = http.createHttp(); 1472httpRequest.request("EXAMPLE_URL").then(data => { 1473 const httpResponseCache = http.createHttpResponseCache(); 1474 httpResponseCache.delete((err: BusinessError) => { 1475 try { 1476 if (err) { 1477 console.error('fail: ' + err); 1478 } else { 1479 console.info('success'); 1480 } 1481 } catch (err) { 1482 console.error('error: ' + err); 1483 } 1484 }); 1485 httpRequest.destroy(); 1486}).catch((error: BusinessError) => { 1487 console.error("errocode" + JSON.stringify(error)); 1488}); 1489``` 1490 1491### delete<sup>9+</sup> 1492 1493delete(): Promise\<void\> 1494 1495Disables the cache and deletes the data in it. This API uses a promise to return the result. 1496 1497**Atomic service API**: This API can be used in atomic services since API version 11. 1498 1499**System capability**: SystemCapability.Communication.NetStack 1500 1501**Return value** 1502 1503| Type | Description | 1504| --------------------------------- | ------------------------------------- | 1505| Promise\<void\> | Promise used to return the result.| 1506 1507**Example** 1508 1509```ts 1510import { http } from '@kit.NetworkKit'; 1511import { BusinessError } from '@kit.BasicServicesKit'; 1512 1513let httpRequest = http.createHttp(); 1514httpRequest.request("EXAMPLE_URL").then(data => { 1515 const httpResponseCache = http.createHttpResponseCache(); 1516 httpResponseCache.delete().then(() => { 1517 console.log("success"); 1518 }).catch((err: BusinessError) => { 1519 console.error("fail"); 1520 }); 1521 httpRequest.destroy(); 1522}).catch((error: BusinessError) => { 1523 console.error("errocode" + JSON.stringify(error)); 1524}); 1525``` 1526 1527## HttpDataType<sup>9+</sup> 1528 1529Enumerates HTTP data types. 1530 1531**Atomic service API**: This API can be used in atomic services since API version 11. 1532 1533**System capability**: SystemCapability.Communication.NetStack 1534 1535| Name| Value| Description | 1536| ------------------ | -- | ----------- | 1537| STRING | 0 | String type.| 1538| OBJECT | 1 | Object type. | 1539| ARRAY_BUFFER | 2 | Binary array type.| 1540 1541## HttpProtocol<sup>9+</sup> 1542 1543Enumerates HTTP protocol versions. 1544 1545**System capability**: SystemCapability.Communication.NetStack 1546 1547| Name | Value | Description | 1548| :-------- | :----------- | :----------- | 1549| HTTP1_1 | 0 | HTTP1.1<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 1550| HTTP2 | 1 | HTTP2<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 1551| 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.| 1552 1553## CertType<sup>11+</sup> 1554 1555Enumerates certificate types. 1556 1557**System capability**: SystemCapability.Communication.NetStack 1558 1559| Name| Value | Description | 1560| --- | ------ | ---------- | 1561| PEM | PEM | PEM certificate.| 1562| DER | DER | DER certificate.| 1563| P12 | P12 | P12 certificate.| 1564 1565## CertificatePinning<sup>12+</sup> 1566 1567Defines the dynamic configuration of certificate pinning. 1568 1569**System capability**: SystemCapability.Communication.NetStack 1570 1571| Name | Type | Mandatory |Description | 1572| ------------------ |---- |-- | ----------- | 1573| publicKeyHash | string | Yes|Certificate PIN of the string type.| 1574| hashAlgorithm | 'SHA-256' | Yes |Encryption algorithm. Currently, only SHA-256 is supported.| 1575 1576## HttpProxy<sup>10+</sup> 1577 1578type HttpProxy = connection.HttpProxy 1579 1580Defines the network proxy configuration. 1581 1582**Atomic service API**: This API can be used in atomic services since API version 11. 1583 1584**System capability**: SystemCapability.Communication.NetStack 1585 1586| Type | Description | 1587| ---------------- | --------------------------- | 1588| connection.HttpProxy | Network proxy configuration. | 1589 1590## AddressFamily<sup>15+</sup> 1591 1592Enumerates the address types for domain name resolution. 1593 1594**System capability**: SystemCapability.Communication.NetStack 1595 1596| Name | Value | Description | 1597| ---------------- | --------------- | --------------------------- | 1598| DEFAULT | CURL_IPRESOLVE_WHATEVER | Automatically selects the IPv4 or IPv6 address of the target domain name. | 1599| ONLY_V4 | CURL_IPRESOLVE_V4 | Resolves only the IPv4 address of the target domain name and ignores the IPv6 address. | 1600| ONLY_V6 | CURL_IPRESOLVE_V6 | Resolves only the IPv6 address of the target domain name and ignores the IPv4 address. | 1601 1602## RemoteValidation<sup>18+</sup> 1603 1604type RemoteValidation = 'system' | 'skip' 1605 1606Certificate 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. 1607 1608**Atomic service API**: This API can be used in atomic services since API version 18. 1609 1610**System capability**: SystemCapability.Communication.NetStack 1611 1612| Type | Description | 1613| ---------------- |---------------| 1614| 'system' | Use of the system CA for verification.| 1615| 'skip' | Skipping of CA verification. | 1616 1617## Credential<sup>18+</sup> 1618 1619Represents the credential used for server identity verification in a session, including the user name and password. 1620 1621**Atomic service API**: This API can be used in atomic services since API version 18. 1622 1623**System capability**: SystemCapability.Communication.NetStack 1624 1625| Name | Type | Read Only | Optional |Description | 1626| ------------------ |---- |-- | -- |----------- | 1627| username | string | No|No|User name used for verification. The default value is **''**.| 1628| password | string | No |No|Password used for verification. The default value is **''**.| 1629 1630## ServerAuthentication<sup>18+</sup> 1631 1632Defines HTTP server identity verification information. 1633 1634**Atomic service API**: This API can be used in atomic services since API version 18. 1635 1636**System capability**: SystemCapability.Communication.NetStack 1637 1638| Name | Type | Read Only | Optional |Description | 1639| ------------------ |-------------------------------------------------|-------- |------------ |---------------| 1640| credential | [Credential](#credential18) | No | No |Server credential. The default value is **undefined**. | 1641| authenticationType | [AuthenticationType](#authenticationtype18) | No | Yes | Server identity verification type. If the type is not set, negotiation with the server is required. | 1642 1643 1644## TlsConfig<sup>18+</sup> 1645 1646Defines the the TLS configuration, including the version and cipher suite. 1647 1648**Atomic service API**: This API can be used in atomic services since API version 18. 1649 1650**System capability**: SystemCapability.Communication.NetStack 1651 1652| Name | Type | Read Only | Optional |Description | 1653| ------------------ |---------------------------------|-------- |-------- |---------------| 1654| tlsVersionMin | [TlsVersion](#tlsversion18) | No |No | Earliest TLS version. | 1655| tlsVersionMax | [TlsVersion](#tlsversion18) | No |No | Latest TLS version. | 1656| cipherSuites | [CipherSuite](#ciphersuite18)[] | No |Yes | Array of cipher suite types.| 1657 1658## TlsVersion<sup>18+</sup> 1659 1660Enumerates TLS versions. 1661 1662**Atomic service API**: This API can be used in atomic services since API version 18. 1663 1664**System capability**: SystemCapability.Communication.NetStack 1665 1666| Name | Value| Description | 1667|:----------|:--|:-----------| 1668| TLS_V_1_0 | 4 | TLS version 1.0.| 1669| TLS_V_1_1 | 5 | TLS version 1.1.| 1670| TLS_V_1_2 | 6 | TLS version 1.2.| 1671| TLS_V_1_3 | 7 | TLS version 1.3.| 1672 1673## TlsOptions<sup>18+</sup> 1674 1675type TlsOptions = 'system' | TlsConfig 1676 1677Defines the TLS configuration. 1678 1679**Atomic service API**: This API can be used in atomic services since API version 18. 1680 1681**System capability**: SystemCapability.Communication.NetStack 1682 1683| Type | Description | 1684|-------------------------------|------------------------------------------------------------------------------------| 1685| 'system' | TLS version of the system. This field is defaulted to **system** when the value is not set.| 1686| TlsOptions | Custom TLS version and cipher suites.| 1687 1688## RemoteValidation<sup>18+</sup> 1689 1690type RemoteValidation = 'system' | 'skip' 1691 1692Enumerates the identity verification modes of the remote server. 1693 1694**Atomic service API**: This API can be used in atomic services since API version 18. 1695 1696**System capability**: SystemCapability.Communication.NetStack 1697 1698| Type | Description | 1699|-------------------------------|------------------------------------------------------------------------------------| 1700| 'system' | Use of the system CA. This field is defaulted to **system** when the value is not set.| 1701| 'skip' | Skipping of CA verification. This field has a fixed value of **skip**.| 1702 1703## AuthenticationType<sup>18+</sup> 1704 1705type AuthenticationType = 'basic' | 'ntlm' | 'digest' 1706 1707Enumerates server authentication modes in a session. 1708 1709**Atomic service API**: This API can be used in atomic services since API version 18. 1710 1711**System capability**: SystemCapability.Communication.NetStack 1712 1713|Type | Description | 1714|-------------------------------|----------------------------------------------------------------------------------------------------| 1715| 'basic' | Basic authentication mode. This field has a fixed value of **basic**.| 1716| 'ntlm' | NTLM authentication mode. This field has a fixed value of **ntlm**.| 1717| 'digest' | Digest authentication mode. This field has a fixed value of **digest**.| 1718 1719## CipherSuite<sup>18+</sup> 1720 1721type CipherSuite = TlsV13CipherSuite 1722 1723Declares the cipher suite. 1724 1725**Atomic service API**: This API can be used in atomic services since API version 18. 1726 1727**System capability**: SystemCapability.Communication.NetStack 1728 1729| Type | Description | 1730| ---------------- |-------------------------------------------------------------------| 1731| TlsV13CipherSuite | Cipher suite defined in [TlsV13CipherSuite](#tlsv13ciphersuite18). | 1732 1733## TlsV13CipherSuite<sup>18+</sup> 1734 1735type TlsV13CipherSuite = TlsV12CipherSuite | TlsV13SpecificCipherSuite 1736 1737Declares the cipher suite for TLS 1.3, which is also compatible with TLS 1.2. 1738 1739**Atomic service API**: This API can be used in atomic services since API version 18. 1740 1741**System capability**: SystemCapability.Communication.NetStack 1742 1743| Type | Description | 1744| ---------------- |-------------------------------------------------------------------| 1745| TlsV12CipherSuite | [TlsV11CipherSuite](#tlsv11ciphersuite18). | 1746| TlsV13SpecificCipherSuite | [TlsV13SpecificCipherSuite](#tlsv13specificciphersuite18).| 1747 1748## TlsV12CipherSuite<sup>18+</sup> 1749 1750type TlsV12CipherSuite = TlsV11CipherSuite | TlsV12SpecificCipherSuite 1751 1752Declares the cipher suite for TLS 1.2, which is also compatible with TLS 1.1. 1753 1754**Atomic service API**: This API can be used in atomic services since API version 18. 1755 1756**System capability**: SystemCapability.Communication.NetStack 1757 1758| Type | Description | 1759| ---------------- |-------------------------------------------------------------------| 1760| TlsV11CipherSuite | [TlsV11CipherSuite](#tlsv11ciphersuite18). | 1761| TlsV12SpecificCipherSuite | [TlsV12SpecificCipherSuite](#tlsv12specificciphersuite18).| 1762 1763## TlsV11CipherSuite<sup>18+</sup> 1764 1765type TlsV11CipherSuite = TlsV10CipherSuite 1766 1767Declares the cipher suite for TLS 1.1, which is the same as that for TLS1.0. 1768 1769**Atomic service API**: This API can be used in atomic services since API version 18. 1770 1771**System capability**: SystemCapability.Communication.NetStack 1772 1773| Type | Description | 1774| ---------------- |---------------------------------------------------| 1775| TlsV10CipherSuite | [TlsV10CipherSuite](#tlsv10ciphersuite18).| 1776 1777## TlsV10CipherSuite<sup>18+</sup> 1778 1779type TlsV10CipherSuite = TlsV10SpecificCipherSuite 1780 1781Declares the cipher suite for TLS 1.0. 1782 1783**Atomic service API**: This API can be used in atomic services since API version 18. 1784 1785**System capability**: SystemCapability.Communication.NetStack 1786 1787| Type | Description | 1788| ---------------- |-------------------------------------------------------------------| 1789| TlsV10SpecificCipherSuite | [TlsV10SpecificCipherSuite](#tlsv10specificciphersuite18).| 1790 1791## TlsV13SpecificCipherSuite<sup>18+</sup> 1792 1793type TlsV13SpecificCipherSuite = 'TLS_AES_128_GCM_SHA256' | 'TLS_AES_256_GCM_SHA384' | 'TLS_CHACHA20_POLY1305_SHA256' 1794 1795Enumerates cipher suites supported by TLS 1.3 or later. 1796 1797**Atomic service API**: This API can be used in atomic services since API version 18. 1798 1799**System capability**: SystemCapability.Communication.NetStack 1800 1801| Type | Description | 1802| ---------------- |------| 1803| 'TLS_AES_128_GCM_SHA256' | Supported cipher suite: TLS_AES_128_GCM_SHA256. The value is a string.| 1804| 'TLS_AES_256_GCM_SHA384' | Supported cipher suite: TLS_AES_256_GCM_SHA384. The value is a string.| 1805| 'TLS_CHACHA20_POLY1305_SHA256' | Supported cipher suite: TLS_CHACHA20_POLY1305_SHA256. The value is a string.| 1806 1807## TlsV12SpecificCipherSuite<sup>18+</sup> 1808 1809type TlsV12SpecificCipherSuite = 'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256' | 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256' | 1810'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384' | 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384' | 1811'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256' | 'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256' | 1812'TLS_RSA_WITH_AES_128_GCM_SHA256' | 'TLS_RSA_WITH_AES_256_GCM_SHA384' 1813 1814Enumerates cipher suites supported by TLS 1.2 or later. 1815 1816**Atomic service API**: This API can be used in atomic services since API version 18. 1817 1818**System capability**: SystemCapability.Communication.NetStack 1819 1820| Type | Description | 1821| ---------------- |------| 1822| 'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256' | Supported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256. The value is a string.| 1823| 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256' | Supported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256. The value is a string.| 1824| 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384' | Supported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384. The value is a string.| 1825| 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384' | Supported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384. The value is a string.| 1826| 'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256' | Supported cipher suite: TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256. The value is a string.| 1827| 'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256' | Supported cipher suite: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256. The value is a string.| 1828| 'TLS_RSA_WITH_AES_128_GCM_SHA256' | Supported cipher suite: TLS_RSA_WITH_AES_128_GCM_SHA256. The value is a string.| 1829| 'TLS_RSA_WITH_AES_256_GCM_SHA384' | Supported cipher suite: TLS_RSA_WITH_AES_256_GCM_SHA384. The value is a string.| 1830 1831## TlsV10SpecificCipherSuite<sup>18+</sup> 1832 1833type TlsV10SpecificCipherSuite = 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA' | 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA' | 1834'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA' | 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA' | 'TLS_RSA_WITH_AES_128_CBC_SHA' | 1835'TLS_RSA_WITH_AES_256_CBC_SHA' | 'TLS_RSA_WITH_3DES_EDE_CBC_SHA' 1836 1837Enumerates cipher suites supported by TLS 1.0 or later. 1838 1839**Atomic service API**: This API can be used in atomic services since API version 18. 1840 1841**System capability**: SystemCapability.Communication.NetStack 1842 1843| Type | Description | 1844| ---------------- |------| 1845| 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA' | Supported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA. The value is a string.| 1846| 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA' | Supported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA. The value is a string.| 1847| 'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA' | Supported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA. The value is a string.| 1848| 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA' | Supported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA. The value is a string.| 1849| 'TLS_RSA_WITH_AES_128_CBC_SHA' | Supported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA. The value is a string.| 1850| 'TLS_RSA_WITH_AES_256_CBC_SHA' | Supported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA. The value is a string.| 1851| 'TLS_RSA_WITH_3DES_EDE_CBC_SHA' | Supported cipher suite: TLS_RSA_WITH_3DES_EDE_CBC_SHA. The value is a string.| 1852