1# @ohos.net.http (Data Request) 2 3The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. 4 5> **NOTE** 6> 7>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. 8> 9 10## Modules to Import 11 12```ts 13import http from '@ohos.net.http'; 14``` 15 16## Examples 17 18```ts 19// Import the http namespace. 20import http from '@ohos.net.http'; 21import { BusinessError } from '@ohos.base'; 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 31class ExtraData { 32 public data: string; 33 34 constructor(data: string) { 35 this.data = data; 36 } 37} 38 39class Header { 40 public contentType: string; 41 42 constructor(contentType: string) { 43 this.contentType = contentType; 44 } 45} 46 47httpRequest.request( // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. 48 "EXAMPLE_URL", 49 { 50 method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. 51 // This parameter is used to transfer data when the POST request is used. 52 extraData: new ExtraData('data to send'), 53 expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data. 54 usingCache: true, // Optional. The default value is true. 55 priority: 1, // Optional. The default value is 1. 56 // You can add header fields based on service requirements. 57 header: new Header('application/json'), 58 readTimeout: 60000, // Optional. The default value is 60000, in ms. 59 connectTimeout: 60000 // Optional. The default value is 60000, in ms. 60 usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. 61 usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API version 10. 62 caPath: "", // Optional. The preset CA certificate is used by default. This field is supported since API version 10. 63 }, 64 (err: BusinessError, data: http.HttpResponse) => { 65 if (!err) { 66 // data.result carries the HTTP response. Parse the response based on service requirements. 67 console.info('Result:' + JSON.stringify(data.result)); 68 console.info('code:' + JSON.stringify(data.responseCode)); 69 console.info('type:' + JSON.stringify(data.resultType)); 70 // data.header carries the HTTP response header. Parse the content based on service requirements. 71 console.info('header:' + JSON.stringify(data.header)); 72 console.info('cookies:' + JSON.stringify(data.cookies)); // Cookies are supported since API version 8. 73 // Unsubscribe from HTTP Response Header events. 74 httpRequest.off('headersReceive'); 75 // Call destroy() to destroy the JavaScript object after the HTTP request is complete. 76 httpRequest.destroy(); 77 } else { 78 console.info('error:' + JSON.stringify(err)); 79 // Unsubscribe from HTTP Response Header events. 80 httpRequest.off('headersReceive'); 81 // Call destroy() to destroy the JavaScript object after the HTTP request is complete. 82 httpRequest.destroy(); 83 } 84 }); 85``` 86 87> **NOTE** 88> If the data in **console.info()** contains a newline character, the data will be truncated. 89 90## http.createHttp 91 92createHttp(): HttpRequest 93 94Creates 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. 95 96> **NOTE** 97> Call the **destroy()** method to release resources after the HttpRequest is complete. 98 99**System capability**: SystemCapability.Communication.NetStack 100 101**Return value** 102 103| Type | Description | 104| :---------- | :----------------------------------------------------------- | 105| HttpRequest | **HttpRequest** object, which contains the **request**, **requestInStream**, **destroy**, **on**, or **off** method.| 106 107**Example** 108 109```ts 110import http from '@ohos.net.http'; 111 112let httpRequest = http.createHttp(); 113``` 114 115## HttpRequest 116 117Defines an HTTP request task. Before invoking methods of **HttpRequest**, you must call **createHttp()** to create an HTTP request task. 118 119### request 120 121request(url: string, callback: AsyncCallback\<HttpResponse\>): void 122 123Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. 124 125> **NOTE** 126> This API supports only receiving of data not greater than 5 MB. 127 128**Required permissions**: ohos.permission.INTERNET 129 130**System capability**: SystemCapability.Communication.NetStack 131 132**Parameters** 133 134| Name | Type | Mandatory| Description | 135| -------- | ---------------------------------------------- | ---- | ---------------------- | 136| url | string | Yes | URL for initiating an HTTP request.| 137| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | 138 139**Error codes** 140 141| ID | Error Message | 142|---------|-------------------------------------------------------| 143| 401 | Parameter error. | 144| 201 | Permission denied. | 145| 2300001 | Unsupported protocol. | 146| 2300003 | URL using bad/illegal format or missing URL. | 147| 2300005 | Couldn't resolve proxy name. | 148| 2300006 | Couldn't resolve host name. | 149| 2300007 | Couldn't connect to server. | 150| 2300008 | Weird server reply. | 151| 2300009 | Access denied to remote resource. | 152| 2300016 | Error in the HTTP2 framing layer. | 153| 2300018 | Transferred a partial file. | 154| 2300023 | Failed writing received data to disk/application. | 155| 2300025 | Upload failed. | 156| 2300026 | Failed to open/read local data from file/application. | 157| 2300027 | Out of memory. | 158| 2300028 | Timeout was reached. | 159| 2300047 | Number of redirects hit maximum amount. | 160| 2300052 | Server returned nothing (no headers, no data). | 161| 2300055 | Failed sending data to the peer. | 162| 2300056 | Failure when receiving data from the peer. | 163| 2300058 | Problem with the local SSL certificate. | 164| 2300059 | Couldn't use specified SSL cipher. | 165| 2300060 | SSL peer certificate or SSH remote key was not OK. | 166| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 167| 2300063 | Maximum file size exceeded. | 168| 2300070 | Disk full or allocation exceeded. | 169| 2300073 | Remote file already exists. | 170| 2300077 | Problem with the SSL CA cert (path? access rights?). | 171| 2300078 | Remote file not found. | 172| 2300094 | An authentication function returned an error. | 173| 2300999 | Unknown Other Error. | 174 175> **NOTE** 176> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). 177> 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). 178 179**Example** 180 181```ts 182import http from '@ohos.net.http'; 183 184let httpRequest = http.createHttp(); 185httpRequest.request("EXAMPLE_URL", (err: Error, data: http.HttpResponse) => { 186 if (!err) { 187 console.info('Result:' + data.result); 188 console.info('code:' + data.responseCode); 189 console.info('type:' + JSON.stringify(data.resultType)); 190 console.info('header:' + JSON.stringify(data.header)); 191 console.info('cookies:' + data.cookies); // Cookies are supported since API version 8. 192 } else { 193 console.info('error:' + JSON.stringify(err)); 194 } 195}); 196``` 197 198### request 199 200request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpResponse\>):void 201 202Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. 203 204> **NOTE** 205> This API supports only receiving of data not greater than 5 MB. 206 207**Required permissions**: ohos.permission.INTERNET 208 209**System capability**: SystemCapability.Communication.NetStack 210 211**Parameters** 212 213| Name | Type | Mandatory| Description | 214| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 215| url | string | Yes | URL for initiating an HTTP request. | 216| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 217| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | 218 219**Error codes** 220 221| ID | Error Message | 222|---------|-------------------------------------------------------| 223| 401 | Parameter error. | 224| 201 | Permission denied. | 225| 2300001 | Unsupported protocol. | 226| 2300003 | URL using bad/illegal format or missing URL. | 227| 2300005 | Couldn't resolve proxy name. | 228| 2300006 | Couldn't resolve host name. | 229| 2300007 | Couldn't connect to server. | 230| 2300008 | Weird server reply. | 231| 2300009 | Access denied to remote resource. | 232| 2300016 | Error in the HTTP2 framing layer. | 233| 2300018 | Transferred a partial file. | 234| 2300023 | Failed writing received data to disk/application. | 235| 2300025 | Upload failed. | 236| 2300026 | Failed to open/read local data from file/application. | 237| 2300027 | Out of memory. | 238| 2300028 | Timeout was reached. | 239| 2300047 | Number of redirects hit maximum amount. | 240| 2300052 | Server returned nothing (no headers, no data). | 241| 2300055 | Failed sending data to the peer. | 242| 2300056 | Failure when receiving data from the peer. | 243| 2300058 | Problem with the local SSL certificate. | 244| 2300059 | Couldn't use specified SSL cipher. | 245| 2300060 | SSL peer certificate or SSH remote key was not OK. | 246| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 247| 2300063 | Maximum file size exceeded. | 248| 2300070 | Disk full or allocation exceeded. | 249| 2300073 | Remote file already exists. | 250| 2300077 | Problem with the SSL CA cert (path? access rights?). | 251| 2300078 | Remote file not found. | 252| 2300094 | An authentication function returned an error. | 253| 2300999 | Unknown Other Error. | 254 255> **NOTE** 256> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). 257> 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). 258 259**Example** 260 261```ts 262import http from '@ohos.net.http'; 263 264class Header { 265 public contentType: string; 266 267 constructor(contentType: string) { 268 this.contentType = contentType; 269 } 270} 271 272let httpRequest = http.createHttp(); 273let promise = httpRequest.request("EXAMPLE_URL", { 274 method: http.RequestMethod.GET, 275 connectTimeout: 60000, 276 readTimeout: 60000, 277 header: new Header('application/json') 278}); 279 280promise.then((data:http.HttpResponse) => { 281 console.info('Result:' + data.result); 282 console.info('code:' + data.responseCode); 283 console.info('type:' + JSON.stringify(data.resultType)); 284 console.info('header:' + JSON.stringify(data.header)); 285 console.info('cookies:' + data.cookies); // Cookies are supported since API version 8. 286 console.info('header.content-Type:' + data.header); 287 console.info('header.Status-Line:' + data.header); 288 289}).catch((err:Error) => { 290 console.info('error:' + JSON.stringify(err)); 291}); 292``` 293 294### request 295 296request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\> 297 298Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. 299 300> **NOTE** 301> This API supports only receiving of data not greater than 5 MB. 302 303**Required permissions**: ohos.permission.INTERNET 304 305**System capability**: SystemCapability.Communication.NetStack 306 307**Parameters** 308 309| Name | Type | Mandatory| Description | 310| ------- | ------------------ | ---- | ----------------------------------------------- | 311| url | string | Yes | URL for initiating an HTTP request. | 312| options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 313 314**Return value** 315 316| Type | Description | 317| :------------------------------------- | :-------------------------------- | 318| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| 319 320**Error codes** 321 322| ID | Error Message | 323|---------|-------------------------------------------------------| 324| 401 | Parameter error. | 325| 201 | Permission denied. | 326| 2300001 | Unsupported protocol. | 327| 2300003 | URL using bad/illegal format or missing URL. | 328| 2300005 | Couldn't resolve proxy name. | 329| 2300006 | Couldn't resolve host name. | 330| 2300007 | Couldn't connect to server. | 331| 2300008 | Weird server reply. | 332| 2300009 | Access denied to remote resource. | 333| 2300016 | Error in the HTTP2 framing layer. | 334| 2300018 | Transferred a partial file. | 335| 2300023 | Failed writing received data to disk/application. | 336| 2300025 | Upload failed. | 337| 2300026 | Failed to open/read local data from file/application. | 338| 2300027 | Out of memory. | 339| 2300028 | Timeout was reached. | 340| 2300047 | Number of redirects hit maximum amount. | 341| 2300052 | Server returned nothing (no headers, no data). | 342| 2300055 | Failed sending data to the peer. | 343| 2300056 | Failure when receiving data from the peer. | 344| 2300058 | Problem with the local SSL certificate. | 345| 2300059 | Couldn't use specified SSL cipher. | 346| 2300060 | SSL peer certificate or SSH remote key was not OK. | 347| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 348| 2300063 | Maximum file size exceeded. | 349| 2300070 | Disk full or allocation exceeded. | 350| 2300073 | Remote file already exists. | 351| 2300077 | Problem with the SSL CA cert (path? access rights?). | 352| 2300078 | Remote file not found. | 353| 2300094 | An authentication function returned an error. | 354| 2300999 | Unknown Other Error. | 355 356> **NOTE** 357> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). 358> 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). 359 360**Example** 361 362```ts 363import http from '@ohos.net.http'; 364 365class Header { 366 public contentType: string; 367 368 constructor(contentType: string) { 369 this.contentType = contentType; 370 } 371} 372 373let httpRequest = http.createHttp(); 374let promise = httpRequest.request("EXAMPLE_URL", { 375 method: http.RequestMethod.GET, 376 connectTimeout: 60000, 377 readTimeout: 60000, 378 header: new Header('application/json') 379}); 380promise.then((data:http.HttpResponse) => { 381 console.info('Result:' + data.result); 382 console.info('code:' + data.responseCode); 383 console.info('type:' + JSON.stringify(data.resultType)); 384 console.info('header:' + JSON.stringify(data.header)); 385 console.info('cookies:' + data.cookies); // Cookies are supported since API version 8. 386 console.info('header.content-Type:' + data.header); 387 console.info('header.Status-Line:' + data.header); 388}).catch((err:Error) => { 389 console.info('error:' + JSON.stringify(err)); 390}); 391``` 392 393### destroy 394 395destroy(): void 396 397Destroys an HTTP request. 398 399**System capability**: SystemCapability.Communication.NetStack 400 401**Example** 402 403```ts 404import http from '@ohos.net.http'; 405let httpRequest = http.createHttp(); 406 407httpRequest.destroy(); 408``` 409 410### requestInStream<sup>10+</sup> 411 412requestInStream(url: string, callback: AsyncCallback\<number\>): void 413 414Initiates 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. 415 416**Required permissions**: ohos.permission.INTERNET 417 418**System capability**: SystemCapability.Communication.NetStack 419 420**Parameters** 421 422| Name | Type | Mandatory| Description | 423| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 424| url | string | Yes | URL for initiating an HTTP request. | 425| callback | AsyncCallback\<number\> | Yes | Callback used to return the result. | 426 427**Error codes** 428 429| ID | Error Message | 430|---------|-------------------------------------------------------| 431| 401 | Parameter error. | 432| 201 | Permission denied. | 433| 2300001 | Unsupported protocol. | 434| 2300003 | URL using bad/illegal format or missing URL. | 435| 2300005 | Couldn't resolve proxy name. | 436| 2300006 | Couldn't resolve host name. | 437| 2300007 | Couldn't connect to server. | 438| 2300008 | Weird server reply. | 439| 2300009 | Access denied to remote resource. | 440| 2300016 | Error in the HTTP2 framing layer. | 441| 2300018 | Transferred a partial file. | 442| 2300023 | Failed writing received data to disk/application. | 443| 2300025 | Upload failed. | 444| 2300026 | Failed to open/read local data from file/application. | 445| 2300027 | Out of memory. | 446| 2300028 | Timeout was reached. | 447| 2300047 | Number of redirects hit maximum amount. | 448| 2300052 | Server returned nothing (no headers, no data). | 449| 2300055 | Failed sending data to the peer. | 450| 2300056 | Failure when receiving data from the peer. | 451| 2300058 | Problem with the local SSL certificate. | 452| 2300059 | Couldn't use specified SSL cipher. | 453| 2300060 | SSL peer certificate or SSH remote key was not OK. | 454| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 455| 2300063 | Maximum file size exceeded. | 456| 2300070 | Disk full or allocation exceeded. | 457| 2300073 | Remote file already exists. | 458| 2300077 | Problem with the SSL CA cert (path? access rights?). | 459| 2300078 | Remote file not found. | 460| 2300094 | An authentication function returned an error. | 461| 2300999 | Unknown Other Error. | 462 463> **NOTE** 464> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). 465> 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). 466 467**Example** 468 469```ts 470import http from '@ohos.net.http'; 471import { BusinessError } from '@ohos.base'; 472 473let httpRequest = http.createHttp(); 474httpRequest.requestInStream("EXAMPLE_URL", (err: BusinessError, data: number) => { 475 if (!err) { 476 console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); 477 } else { 478 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 479 } 480}) 481``` 482 483### requestInStream<sup>10+</sup> 484 485requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void 486 487Initiates 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. 488 489**Required permissions**: ohos.permission.INTERNET 490 491**System capability**: SystemCapability.Communication.NetStack 492 493**Parameters** 494 495| Name | Type | Mandatory| Description | 496| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 497| url | string | Yes | URL for initiating an HTTP request. | 498| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 499| callback | AsyncCallback\<[number](#responsecode)\> | Yes | Callback used to return the result. | 500 501**Error codes** 502 503| ID | Error Message | 504|---------|-------------------------------------------------------| 505| 401 | Parameter error. | 506| 201 | Permission denied. | 507| 2300001 | Unsupported protocol. | 508| 2300003 | URL using bad/illegal format or missing URL. | 509| 2300005 | Couldn't resolve proxy name. | 510| 2300006 | Couldn't resolve host name. | 511| 2300007 | Couldn't connect to server. | 512| 2300008 | Weird server reply. | 513| 2300009 | Access denied to remote resource. | 514| 2300016 | Error in the HTTP2 framing layer. | 515| 2300018 | Transferred a partial file. | 516| 2300023 | Failed writing received data to disk/application. | 517| 2300025 | Upload failed. | 518| 2300026 | Failed to open/read local data from file/application. | 519| 2300027 | Out of memory. | 520| 2300028 | Timeout was reached. | 521| 2300047 | Number of redirects hit maximum amount. | 522| 2300052 | Server returned nothing (no headers, no data). | 523| 2300055 | Failed sending data to the peer. | 524| 2300056 | Failure when receiving data from the peer. | 525| 2300058 | Problem with the local SSL certificate. | 526| 2300059 | Couldn't use specified SSL cipher. | 527| 2300060 | SSL peer certificate or SSH remote key was not OK. | 528| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 529| 2300063 | Maximum file size exceeded. | 530| 2300070 | Disk full or allocation exceeded. | 531| 2300073 | Remote file already exists. | 532| 2300077 | Problem with the SSL CA cert (path? access rights?). | 533| 2300078 | Remote file not found. | 534| 2300094 | An authentication function returned an error. | 535| 2300999 | Unknown Other Error. | 536 537> **NOTE** 538> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). 539> 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). 540 541**Example** 542 543```ts 544import http from '@ohos.net.http'; 545import { BusinessError } from '@ohos.base'; 546 547let httpRequest = http.createHttp(); 548httpRequest.requestInStream("EXAMPLE_URL", (err: BusinessError<void> , data: number) => { 549 if (!err) { 550 console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); 551 } else { 552 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 553 } 554}) 555``` 556 557### requestInStream<sup>10+</sup> 558 559requestInStream(url: string, options? : HttpRequestOptions): Promise\<number\> 560 561Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response. 562 563**Required permissions**: ohos.permission.INTERNET 564 565**System capability**: SystemCapability.Communication.NetStack 566 567**Parameters** 568 569| Name | Type | Mandatory| Description | 570| ------- | ------------------ | ---- | ----------------------------------------------- | 571| url | string | Yes | URL for initiating an HTTP request. | 572| options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 573 574**Return value** 575 576| Type | Description | 577| :------------------------------------- | :-------------------------------- | 578| Promise\<[number](#responsecode)\> | Promise used to return the result.| 579 580**Error codes** 581 582| ID | Error Message | 583|---------|-------------------------------------------------------| 584| 401 | Parameter error. | 585| 201 | Permission denied. | 586| 2300001 | Unsupported protocol. | 587| 2300003 | URL using bad/illegal format or missing URL. | 588| 2300005 | Couldn't resolve proxy name. | 589| 2300006 | Couldn't resolve host name. | 590| 2300007 | Couldn't connect to server. | 591| 2300008 | Weird server reply. | 592| 2300009 | Access denied to remote resource. | 593| 2300016 | Error in the HTTP2 framing layer. | 594| 2300018 | Transferred a partial file. | 595| 2300023 | Failed writing received data to disk/application. | 596| 2300025 | Upload failed. | 597| 2300026 | Failed to open/read local data from file/application. | 598| 2300027 | Out of memory. | 599| 2300028 | Timeout was reached. | 600| 2300047 | Number of redirects hit maximum amount. | 601| 2300052 | Server returned nothing (no headers, no data). | 602| 2300055 | Failed sending data to the peer. | 603| 2300056 | Failure when receiving data from the peer. | 604| 2300058 | Problem with the local SSL certificate. | 605| 2300059 | Couldn't use specified SSL cipher. | 606| 2300060 | SSL peer certificate or SSH remote key was not OK. | 607| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 608| 2300063 | Maximum file size exceeded. | 609| 2300070 | Disk full or allocation exceeded. | 610| 2300073 | Remote file already exists. | 611| 2300077 | Problem with the SSL CA cert (path? access rights?). | 612| 2300078 | Remote file not found. | 613| 2300094 | An authentication function returned an error. | 614| 2300999 | Unknown Other Error. | 615 616> **NOTE** 617> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). 618> 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). 619 620**Example** 621 622```ts 623import http from '@ohos.net.http'; 624 625class Header { 626 public contentType: string; 627 628 constructor(contentType: string) { 629 this.contentType = contentType; 630 } 631} 632 633let httpRequest = http.createHttp(); 634let promise = httpRequest.requestInStream("EXAMPLE_URL", { 635 method: http.RequestMethod.GET, 636 connectTimeout: 60000, 637 readTimeout: 60000, 638 header: new Header('application/json') 639}); 640promise.then((data: number) => { 641 console.info("requestInStream OK!" + data); 642}).catch((err: Error) => { 643 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 644}); 645``` 646 647### on("headerReceive")<sup>(deprecated)</sup> 648 649on(type: "headerReceive", callback: AsyncCallback\<Object\>): void 650 651Registers an observer for HTTP Response Header events. 652 653> **NOTE** 654> This API has been deprecated. You are advised to use [on("headersReceive")<sup>8+</sup>](#onheadersreceive8). 655 656**System capability**: SystemCapability.Communication.NetStack 657 658**Parameters** 659 660| Name | Type | Mandatory| Description | 661| -------- | ----------------------- | ---- | --------------------------------- | 662| type | string | Yes | Event type. The value is **headerReceive**.| 663| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. | 664 665**Example** 666 667```ts 668import http from '@ohos.net.http'; 669import { BusinessError } from '@ohos.base'; 670 671let httpRequest = http.createHttp(); 672httpRequest.on("headerReceive", (data: BusinessError) => { 673 console.info("error:" + JSON.stringify(data)); 674}); 675``` 676 677### off("headerReceive")<sup>(deprecated)</sup> 678 679off(type: "headerReceive", callback?: AsyncCallback\<Object\>): void 680 681Unregisters the observer for HTTP Response Header events. 682 683> **NOTE** 684> 685>1. This API has been deprecated. You are advised to use [off("headersReceive")<sup>8+</sup>](#offheadersreceive8). 686> 687>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. 688 689**System capability**: SystemCapability.Communication.NetStack 690 691**Parameters** 692 693| Name | Type | Mandatory| Description | 694| -------- | ----------------------- | ---- | ------------------------------------- | 695| type | string | Yes | Event type. The value is **headerReceive**.| 696| callback | AsyncCallback\<Object\> | No | Callback used to return the result. | 697 698**Example** 699 700```ts 701import http from '@ohos.net.http'; 702 703let httpRequest = http.createHttp(); 704httpRequest.off("headerReceive"); 705``` 706 707### on("headersReceive")<sup>8+</sup> 708 709on(type: "headersReceive", callback: Callback\<Object\>): void 710 711Registers an observer for HTTP Response Header events. 712 713**System capability**: SystemCapability.Communication.NetStack 714 715**Parameters** 716 717| Name | Type | Mandatory| Description | 718| -------- | ------------------ | ---- | ---------------------------------- | 719| type | string | Yes | Event type. The value is **headersReceive**.| 720| callback | Callback\<Object\> | Yes | Callback used to return the result. | 721 722**Example** 723 724```ts 725import http from '@ohos.net.http'; 726 727let httpRequest = http.createHttp(); 728httpRequest.on("headersReceive", (header: Object) => { 729 console.info("header: " + JSON.stringify(header)); 730}); 731httpRequest.off("headersReceive"); 732``` 733 734### off("headersReceive")<sup>8+</sup> 735 736off(type: "headersReceive", callback?: Callback\<Object\>): void 737 738Unregisters the observer for HTTP Response Header events. 739 740> **NOTE** 741> 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. 742 743**System capability**: SystemCapability.Communication.NetStack 744 745**Parameters** 746 747| Name | Type | Mandatory| Description | 748| -------- | ------------------ | ---- | -------------------------------------- | 749| type | string | Yes | Event type. The value is **headersReceive**.| 750| callback | Callback\<Object\> | No | Callback used to return the result. | 751 752**Example** 753 754```ts 755import http from '@ohos.net.http'; 756 757let httpRequest = http.createHttp(); 758httpRequest.on("headersReceive", (header: Object) => { 759 console.info("header: " + JSON.stringify(header)); 760}); 761httpRequest.off("headersReceive"); 762``` 763 764### once("headersReceive")<sup>8+</sup> 765 766once(type: "headersReceive", callback: Callback\<Object\>): void 767 768Registers 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. 769 770**System capability**: SystemCapability.Communication.NetStack 771 772**Parameters** 773 774| Name | Type | Mandatory| Description | 775| -------- | ------------------ | ---- | ---------------------------------- | 776| type | string | Yes | Event type. The value is **headersReceive**.| 777| callback | Callback\<Object\> | Yes | Callback used to return the result. | 778 779**Example** 780 781```ts 782import http from '@ohos.net.http'; 783 784let httpRequest = http.createHttp(); 785httpRequest.once("headersReceive", (header: Object) => { 786 console.info("header: " + JSON.stringify(header)); 787}); 788``` 789 790### on("dataReceive")<sup>10+</sup> 791 792on(type: "dataReceive", callback: Callback\<ArrayBuffer\>): void 793 794Registers an observer for events indicating receiving of HTTP streaming responses. 795 796> **NOTE** 797> Currently, listening for events related to HTTP streaming data upload is not supported. 798 799**System capability**: SystemCapability.Communication.NetStack 800 801**Parameters** 802 803| Name | Type | Mandatory| Description | 804| -------- | ----------------------- | ---- | --------------------------------- | 805| type | string | Yes | Event type. The value is **dataReceive**.| 806| callback | AsyncCallback\<ArrayBuffer\> | Yes | Callback used to return the result. | 807 808**Example** 809 810```ts 811import http from '@ohos.net.http'; 812 813let httpRequest = http.createHttp(); 814httpRequest.on("dataReceive", (data: ArrayBuffer) => { 815 console.info("dataReceive length: " + JSON.stringify(data.byteLength)); 816}); 817httpRequest.off("dataReceive"); 818``` 819 820### off("dataReceive")<sup>10+</sup> 821 822off(type: "dataReceive", callback?: Callback\<ArrayBuffer\>): void 823 824Unregisters the observer for events indicating receiving of HTTP streaming responses. 825 826> **NOTE** 827> 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. 828 829**System capability**: SystemCapability.Communication.NetStack 830 831**Parameters** 832 833| Name | Type | Mandatory| Description | 834| -------- | ------------------ | ---- | -------------------------------------- | 835| type | string | Yes | Event type. The value is **dataReceive**.| 836| callback | Callback\<ArrayBuffer\> | No | Callback used to return the result. | 837 838**Example** 839 840```ts 841import http from '@ohos.net.http'; 842 843let httpRequest = http.createHttp(); 844httpRequest.on("dataReceive", (data: ArrayBuffer) => { 845 console.info("dataReceive length: " + JSON.stringify(data.byteLength)); 846}); 847httpRequest.off("dataReceive"); 848``` 849 850### on("dataEnd")<sup>10+</sup> 851 852on(type: "dataEnd", callback: Callback\<void\>): void 853 854Registers an observer for events indicating completion of receiving HTTP streaming responses. 855 856> **NOTE** 857> Currently, listening for events related to HTTP streaming data upload is not supported. 858 859**System capability**: SystemCapability.Communication.NetStack 860 861**Parameters** 862 863| Name | Type | Mandatory| Description | 864| -------- | ----------------------- | ---- | --------------------------------- | 865| type | string | Yes | Event type. The value is **dataEnd**.| 866| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 867 868**Example** 869 870```ts 871import http from '@ohos.net.http'; 872 873let httpRequest = http.createHttp(); 874httpRequest.on("dataEnd", () => { 875 console.info("Receive dataEnd !"); 876}); 877httpRequest.off("dataEnd"); 878``` 879 880### off("dataEnd")<sup>10+</sup> 881 882off(type: "dataEnd", callback?: Callback\<void\>): void 883 884Unregisters the observer for events indicating completion of receiving HTTP streaming responses. 885 886> **NOTE** 887> 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. 888 889**System capability**: SystemCapability.Communication.NetStack 890 891**Parameters** 892 893| Name | Type | Mandatory| Description | 894| -------- | ------------------ | ---- | -------------------------------------- | 895| type | string | Yes | Event type. The value is **dataEnd**.| 896| callback | Callback\<void\> | No | Callback used to return the result. | 897 898**Example** 899 900```ts 901import http from '@ohos.net.http'; 902 903let httpRequest = http.createHttp(); 904httpRequest.on("dataEnd", () => { 905 console.info("Receive dataEnd !"); 906}); 907httpRequest.off("dataEnd"); 908``` 909 910### on("dataReceiveProgress")<sup>10+</sup> 911 912on(type: "dataReceiveProgress", callback: Callback\<\{ receiveSize: number, totalSize: number \}\>): void 913 914Registers an observer for events indicating progress of receiving HTTP streaming responses. 915 916> **NOTE** 917> Currently, listening for events related to HTTP streaming data upload is not supported. 918 919**System capability**: SystemCapability.Communication.NetStack 920 921**Parameters** 922 923| Name | Type | Mandatory| Description | 924| -------- | ----------------------- | ---- | --------------------------------- | 925| type | string | Yes | Event type. The value is **dataReceiveProgress**.| 926| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.<br>- **receiveSize**: number of received bytes.<br>- **totalSize**: total number of bytes to be received.| 927 928**Example** 929 930```ts 931import http from '@ohos.net.http'; 932 933class RequestData{ 934 receiveSize: number = 2000 935 totalSize: number = 2000 936} 937 938let httpRequest = http.createHttp(); 939httpRequest.on("dataReceiveProgress", (data: RequestData) => { 940 console.info("dataReceiveProgress:" + JSON.stringify(data)); 941}); 942httpRequest.off("dataReceiveProgress"); 943``` 944 945### off("dataReceiveProgress")<sup>10+</sup> 946 947off(type: "dataReceiveProgress", callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void 948 949Unregisters the observer for events indicating progress of receiving HTTP streaming responses. 950 951> **NOTE** 952> 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. 953 954**System capability**: SystemCapability.Communication.NetStack 955 956**Parameters** 957 958| Name | Type | Mandatory| Description | 959| -------- | ------------------ | ---- | -------------------------------------- | 960| type | string | Yes | Event type. The value is **dataReceiveProgress**.| 961| callback | Callback\<{ receiveSize: number, totalSize: number }\> | No | Callback used to return the result. | 962 963**Example** 964 965```ts 966import http from '@ohos.net.http'; 967 968class RequestData{ 969 receiveSize: number = 2000 970 totalSize: number = 2000 971} 972 973let httpRequest = http.createHttp(); 974httpRequest.on("dataReceiveProgress", (data: RequestData) => { 975 console.info("dataReceiveProgress:" + JSON.stringify(data)); 976}); 977httpRequest.off("dataReceiveProgress"); 978``` 979 980## HttpRequestOptions (Cross-Platform Supported) 981 982Specifies the type and value range of the optional parameters in the HTTP request. 983 984**System capability**: SystemCapability.Communication.NetStack 985 986| Name | Type | Mandatory| Description | 987| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 988| method | [RequestMethod](#requestmethod) | No | Request method. The default value is **GET**. | 989| 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 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.| 990| 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.| 991| usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. | 992| priority<sup>9+</sup> | number | No | Priority. The value range is [1,1000]. The default value is **1**. | 993| header | Object | No | HTTP request header. The default value is **{'content-Type': 'application/json'}**. | 994| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms.<br>The value **0** indicates no timeout.| 995| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | 996| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. | 997| usingProxy<sup>10+</sup> | boolean \| HttpProxy | 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.| 998| 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 **Global.getContext().filesDir**. Currently, only **.pem** certificates are supported. | 999 1000## RequestMethod 1001 1002Defines an HTTP request method. 1003 1004**System capability**: SystemCapability.Communication.NetStack 1005 1006| Name | Value | Description | 1007| :------ | ------- | :------------------ | 1008| OPTIONS | "OPTIONS" | OPTIONS method.| 1009| GET | "GET" | GET method. | 1010| HEAD | "HEAD" | HEAD method. | 1011| POST | "POST" | POST method. | 1012| PUT | "PUT" | PUT method. | 1013| DELETE | "DELETE" | DELETE method. | 1014| TRACE | "TRACE" | TRACE method. | 1015| CONNECT | "CONNECT" | CONNECT method.| 1016 1017## ResponseCode 1018 1019Enumerates the response codes for an HTTP request. 1020 1021**System capability**: SystemCapability.Communication.NetStack 1022 1023| Name | Value | Description | 1024| ----------------- | ---- | ------------------------------------------------------------ | 1025| OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. | 1026| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | 1027| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | 1028| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | 1029| 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. | 1030| RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. | 1031| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | 1032| MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. | 1033| 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.| 1034| MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. | 1035| SEE_OTHER | 303 | "See Other." The response to the request can be found under a different URI. | 1036| NOT_MODIFIED | 304 | "Not Modified." The client has performed a conditional GET request and access is allowed, but the content has not been modified. | 1037| USE_PROXY | 305 | "Use Proxy." The requested resource can only be accessed through the proxy. | 1038| BAD_REQUEST | 400 | "Bad Request." The request could not be understood by the server due to incorrect syntax. | 1039| UNAUTHORIZED | 401 | "Unauthorized." The request requires user authentication. | 1040| PAYMENT_REQUIRED | 402 | "Payment Required." This code is reserved for future use. | 1041| FORBIDDEN | 403 | "Forbidden." The server understands the request but refuses to process it. | 1042| NOT_FOUND | 404 | "Not Found." The server does not find anything matching the Request-URI. | 1043| BAD_METHOD | 405 | "Method Not Allowed." The method specified in the request is not allowed for the resource identified by the Request-URI. | 1044| NOT_ACCEPTABLE | 406 | "Not Acceptable." The server cannot fulfill the request according to the content characteristics of the request. | 1045| PROXY_AUTH | 407 | "Proxy Authentication Required." The request requires user authentication with the proxy. | 1046| CLIENT_TIMEOUT | 408 | "Request Timeout." The client fails to generate a request within the timeout period. | 1047| 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. | 1048| GONE | 410 | "Gone." The requested resource has been deleted permanently and is no longer available. | 1049| LENGTH_REQUIRED | 411 | "Length Required." The server refuses to process the request without a defined Content-Length. | 1050| PRECON_FAILED | 412 | "Precondition Failed." The precondition in the request is incorrect. | 1051| 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. | 1052| REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. | 1053| UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. | 1054| INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. | 1055| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | 1056| BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.| 1057| UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. | 1058| 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. | 1059| VERSION | 505 | "HTTP Version Not Supported." The server does not support the HTTP protocol version used in the request. | 1060 1061## HttpResponse 1062 1063Defines the response to an HTTP request. 1064 1065**System capability**: SystemCapability.Communication.NetStack 1066 1067| Name | Type | Mandatory| Description | 1068| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 1069| result | string \| Object<sup>deprecated 8+</sup> \| ArrayBuffer<sup>8+</sup> | 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.| 1070| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. | 1071| 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**.| 1072| 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'];| 1073| cookies<sup>8+</sup> | string | Yes | Cookies returned by the server. | 1074 1075## http.createHttpResponseCache<sup>9+</sup> 1076 1077createHttpResponseCache(cacheSize?: number): HttpResponseCache 1078 1079Creates a default object to store responses to HTTP access requests. 1080 1081**System capability**: SystemCapability.Communication.NetStack 1082 1083**Parameters** 1084 1085| Name | Type | Mandatory| Description | 1086| -------- | --------------------------------------- | ---- | ---------- | 1087| cacheSize | number | No| Cache size. The maximum value is 10\*1024\*1024 (10 MB). By default, the maximum value is used.| 1088 1089**Return value** 1090 1091| Type | Description | 1092| :---------- | :----------------------------------------------------------- | 1093| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.| 1094 1095**Example** 1096 1097```ts 1098import http from '@ohos.net.http'; 1099 1100let httpResponseCache = http.createHttpResponseCache(); 1101``` 1102 1103## HttpResponseCache<sup>9+</sup> 1104 1105Defines 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. 1106 1107### flush<sup>9+</sup> 1108 1109flush(callback: AsyncCallback\<void\>): void 1110 1111Flushes 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). 1112 1113**System capability**: SystemCapability.Communication.NetStack 1114 1115**Parameters** 1116 1117| Name | Type | Mandatory| Description | 1118| -------- | --------------------------------------- | ---- | ---------- | 1119| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| 1120 1121**Example** 1122 1123```ts 1124import http from '@ohos.net.http'; 1125import { BusinessError } from '@ohos.base'; 1126 1127let httpResponseCache = http.createHttpResponseCache(); 1128httpResponseCache.flush((err: BusinessError) => { 1129 if (err) { 1130 console.info('flush fail'); 1131 return; 1132 } 1133 console.info('flush success'); 1134}); 1135``` 1136 1137### flush<sup>9+</sup> 1138 1139flush(): Promise\<void\> 1140 1141Flushes 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. 1142 1143**System capability**: SystemCapability.Communication.NetStack 1144 1145**Return value** 1146 1147| Type | Description | 1148| --------------------------------- | ------------------------------------- | 1149| Promise\<void\> | Promise used to return the result.| 1150 1151**Example** 1152 1153```ts 1154import http from '@ohos.net.http'; 1155import { BusinessError } from '@ohos.base'; 1156 1157let httpResponseCache = http.createHttpResponseCache(); 1158httpResponseCache.flush().then(() => { 1159 console.info('flush success'); 1160}).catch((err: BusinessError) => { 1161 console.info('flush fail'); 1162}); 1163``` 1164 1165### delete<sup>9+</sup> 1166 1167delete(callback: AsyncCallback\<void\>): void 1168 1169Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result. 1170 1171**System capability**: SystemCapability.Communication.NetStack 1172 1173**Parameters** 1174 1175| Name | Type | Mandatory| Description | 1176| -------- | --------------------------------------- | ---- | ---------- | 1177| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| 1178 1179**Example** 1180 1181```ts 1182import http from '@ohos.net.http'; 1183import { BusinessError } from '@ohos.base'; 1184 1185let httpResponseCache = http.createHttpResponseCache(); 1186httpResponseCache.delete((err: BusinessError) => { 1187 if (err) { 1188 console.info('delete fail'); 1189 return; 1190 } 1191 console.info('delete success'); 1192}); 1193``` 1194 1195### delete<sup>9+</sup> 1196 1197delete(): Promise\<void\> 1198 1199Disables the cache and deletes the data in it. This API uses a promise to return the result. 1200 1201**System capability**: SystemCapability.Communication.NetStack 1202 1203**Return value** 1204 1205| Type | Description | 1206| --------------------------------- | ------------------------------------- | 1207| Promise\<void\> | Promise used to return the result.| 1208 1209**Example** 1210 1211```ts 1212import http from '@ohos.net.http'; 1213import { BusinessError } from '@ohos.base'; 1214 1215let httpResponseCache = http.createHttpResponseCache(); 1216httpResponseCache.delete().then(() => { 1217 console.info('delete success'); 1218}).catch((err: Error) => { 1219 console.info('delete fail'); 1220}); 1221``` 1222 1223## HttpDataType<sup>9+</sup> 1224 1225Enumerates HTTP data types. 1226 1227**System capability**: SystemCapability.Communication.NetStack 1228 1229| Name| Value| Description | 1230| ------------------ | -- | ----------- | 1231| STRING | 0 | String type.| 1232| OBJECT | 1 | Object type. | 1233| ARRAY_BUFFER | 2 | Binary array type.| 1234 1235## HttpProtocol<sup>9+</sup> 1236 1237Enumerates HTTP protocol versions. 1238 1239**System capability**: SystemCapability.Communication.NetStack 1240 1241| Name | Description | 1242| :-------- | :----------- | 1243| HTTP1_1 | HTTP1.1 | 1244| HTTP2 | HTTP2 | 1245 1246<!--no_check--> 1247