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