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