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```js 13import http from '@ohos.net.http'; 14``` 15 16## Examples 17 18```js 19// Import the http namespace. 20import http from '@ohos.net.http'; 21 22// Each httpRequest corresponds to an HTTP request task and cannot be reused. 23let httpRequest = http.createHttp(); 24// 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. 25// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. 26httpRequest.on('headersReceive', (header) => { 27 console.info('header: ' + JSON.stringify(header)); 28}); 29httpRequest.request( 30 // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. 31 "EXAMPLE_URL", 32 { 33 method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. 34 // You can add header fields based on service requirements. 35 header: { 36 'Content-Type': 'application/json' 37 }, 38 // This field is used to transfer data when the POST request is used. 39 extraData: { 40 "data": "data to send", 41 }, 42 expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. 43 usingCache: true, // Optional. The default value is true. 44 priority: 1, // Optional. The default value is 1. 45 connectTimeout: 60000 // Optional. The default value is 60000, in ms. 46 readTimeout: 60000, // Optional. The default value is 60000, in ms. 47 usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. 48 }, (err, data) => { 49 if (!err) { 50 // data.result carries the HTTP response. Parse the response based on service requirements. 51 console.info('Result:' + JSON.stringify(data.result)); 52 console.info('code:' + JSON.stringify(data.responseCode)); 53 // data.header carries the HTTP response header. Parse the content based on service requirements. 54 console.info('header:' + JSON.stringify(data.header)); 55 console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ 56 } else { 57 console.info('error:' + JSON.stringify(err)); 58 // Unsubscribe from HTTP Response Header events. 59 httpRequest.off('headersReceive'); 60 // Call the destroy() method to release resources after HttpRequest is complete. 61 httpRequest.destroy(); 62 } 63 } 64); 65``` 66 67## http.createHttp 68 69createHttp(): HttpRequest 70 71Creates 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. 72 73**System capability**: SystemCapability.Communication.NetStack 74 75**Return value** 76 77| Type | Description | 78| :---------- | :----------------------------------------------------------- | 79| HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.| 80 81**Example** 82 83```js 84import http from '@ohos.net.http'; 85let httpRequest = http.createHttp(); 86``` 87 88## HttpRequest 89 90Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp()](#httpcreatehttp) to create an **HttpRequestTask** object. 91 92### request 93 94request(url: string, callback: AsyncCallback\<HttpResponse\>):void 95 96Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. 97 98>**NOTE** 99>This API supports only transfer of data not greater than 5 MB. 100 101**Required permissions**: ohos.permission.INTERNET 102 103**System capability**: SystemCapability.Communication.NetStack 104 105**Parameters** 106 107| Name | Type | Mandatory| Description | 108| -------- | ---------------------------------------------- | ---- | ----------------------- | 109| url | string | Yes | URL for initiating an HTTP request.| 110| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | 111 112**Error codes** 113 114| Code | Error Message | 115|---------|-------------------------------------------------------| 116| 401 | Parameter error. | 117| 201 | Permission denied. | 118| 2300003 | URL using bad/illegal format or missing URL. | 119| 2300007 | Couldn't connect to server. | 120| 2300028 | Timeout was reached. | 121| 2300052 | Server returned nothing (no headers, no data). | 122| 2300999 | Unknown Other Error. | 123 124>**NOTE** 125> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). 126> 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). 127 128**Example** 129 130```js 131httpRequest.request("EXAMPLE_URL", (err, data) => { 132 if (!err) { 133 console.info('Result:' + data.result); 134 console.info('code:' + data.responseCode); 135 console.info('header:' + JSON.stringify(data.header)); 136 console.info('cookies:' + data.cookies); // 8+ 137 } else { 138 console.info('error:' + JSON.stringify(err)); 139 } 140}); 141``` 142 143### request 144 145request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpResponse\>):void 146 147Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. 148 149>**NOTE** 150>This API supports only transfer of data not greater than 5 MB. 151 152**Required permissions**: ohos.permission.INTERNET 153 154**System capability**: SystemCapability.Communication.NetStack 155 156**Parameters** 157 158| Name | Type | Mandatory| Description | 159| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 160| url | string | Yes | URL for initiating an HTTP request. | 161| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 162| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | 163 164**Error codes** 165 166| Code | Error Message | 167|---------|-------------------------------------------------------| 168| 401 | Parameter error. | 169| 201 | Permission denied. | 170| 2300001 | Unsupported protocol. | 171| 2300003 | URL using bad/illegal format or missing URL. | 172| 2300005 | Couldn't resolve proxy name. | 173| 2300006 | Couldn't resolve host name. | 174| 2300007 | Couldn't connect to server. | 175| 2300008 | Weird server reply. | 176| 2300009 | Access denied to remote resource. | 177| 2300016 | Error in the HTTP2 framing layer. | 178| 2300018 | Transferred a partial file. | 179| 2300023 | Failed writing received data to disk/application. | 180| 2300025 | Upload failed. | 181| 2300026 | Failed to open/read local data from file/application. | 182| 2300027 | Out of memory. | 183| 2300028 | Timeout was reached. | 184| 2300047 | Number of redirects hit maximum amount. | 185| 2300052 | Server returned nothing (no headers, no data). | 186| 2300055 | Failed sending data to the peer. | 187| 2300056 | Failure when receiving data from the peer. | 188| 2300058 | Problem with the local SSL certificate. | 189| 2300059 | Couldn't use specified SSL cipher. | 190| 2300060 | SSL peer certificate or SSH remote key was not OK. | 191| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 192| 2300063 | Maximum file size exceeded. | 193| 2300070 | Disk full or allocation exceeded. | 194| 2300073 | Remote file already exists. | 195| 2300077 | Problem with the SSL CA cert (path? access rights?). | 196| 2300078 | Remote file not found. | 197| 2300094 | An authentication function returned an error. | 198| 2300999 | Unknown Other Error. | 199 200>**NOTE** 201> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). 202> 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). 203 204**Example** 205 206```js 207httpRequest.request("EXAMPLE_URL", 208{ 209 method: http.RequestMethod.GET, 210 header: { 211 'Content-Type': 'application/json' 212 }, 213 readTimeout: 60000, 214 connectTimeout: 60000 215}, (err, data) => { 216 if (!err) { 217 console.info('Result:' + data.result); 218 console.info('code:' + data.responseCode); 219 console.info('header:' + JSON.stringify(data.header)); 220 console.info('cookies:' + data.cookies); // 8+ 221 console.info('header.Content-Type:' + data.header['Content-Type']); 222 console.info('header.Status-Line:' + data.header['Status-Line']); 223 } else { 224 console.info('error:' + JSON.stringify(err)); 225 } 226}); 227``` 228 229### request 230 231request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\> 232 233Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. 234 235>**NOTE** 236>This API supports only transfer of data not greater than 5 MB. 237 238**Required permissions**: ohos.permission.INTERNET 239 240**System capability**: SystemCapability.Communication.NetStack 241 242**Parameters** 243 244| Name | Type | Mandatory| Description | 245| ------- | ------------------ | ---- | ----------------------------------------------- | 246| url | string | Yes | URL for initiating an HTTP request. | 247| options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 248 249**Return value** 250 251| Type | Description | 252| :------------------------------------- | :-------------------------------- | 253| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| 254 255**Error codes** 256 257| Code | Error Message | 258|---------|-------------------------------------------------------| 259| 401 | Parameter error. | 260| 201 | Permission denied. | 261| 2300001 | Unsupported protocol. | 262| 2300003 | URL using bad/illegal format or missing URL. | 263| 2300005 | Couldn't resolve proxy name. | 264| 2300006 | Couldn't resolve host name. | 265| 2300007 | Couldn't connect to server. | 266| 2300008 | Weird server reply. | 267| 2300009 | Access denied to remote resource. | 268| 2300016 | Error in the HTTP2 framing layer. | 269| 2300018 | Transferred a partial file. | 270| 2300023 | Failed writing received data to disk/application. | 271| 2300025 | Upload failed. | 272| 2300026 | Failed to open/read local data from file/application. | 273| 2300027 | Out of memory. | 274| 2300028 | Timeout was reached. | 275| 2300047 | Number of redirects hit maximum amount. | 276| 2300052 | Server returned nothing (no headers, no data). | 277| 2300055 | Failed sending data to the peer. | 278| 2300056 | Failure when receiving data from the peer. | 279| 2300058 | Problem with the local SSL certificate. | 280| 2300059 | Couldn't use specified SSL cipher. | 281| 2300060 | SSL peer certificate or SSH remote key was not OK. | 282| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 283| 2300063 | Maximum file size exceeded. | 284| 2300070 | Disk full or allocation exceeded. | 285| 2300073 | Remote file already exists. | 286| 2300077 | Problem with the SSL CA cert (path? access rights?). | 287| 2300078 | Remote file not found. | 288| 2300094 | An authentication function returned an error. | 289| 2300999 | Unknown Other Error. | 290 291>**NOTE** 292> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). 293> 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). 294 295**Example** 296 297```js 298let promise = httpRequest.request("EXAMPLE_URL", { 299 method: http.RequestMethod.GET, 300 connectTimeout: 60000, 301 readTimeout: 60000, 302 header: { 303 'Content-Type': 'application/json' 304 } 305}); 306promise.then((data) => { 307 console.info('Result:' + data.result); 308 console.info('code:' + data.responseCode); 309 console.info('header:' + JSON.stringify(data.header)); 310 console.info('cookies:' + data.cookies); // 8+ 311 console.info('header.Content-Type:' + data.header['Content-Type']); 312 console.info('header.Status-Line:' + data.header['Status-Line']); 313}).catch((err) => { 314 console.info('error:' + JSON.stringify(err)); 315}); 316``` 317 318### destroy 319 320destroy(): void 321 322Destroys an HTTP request. 323 324**System capability**: SystemCapability.Communication.NetStack 325 326**Example** 327 328```js 329httpRequest.destroy(); 330``` 331 332### on('headerReceive') 333 334on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void 335 336Registers an observer for HTTP Response Header events. 337 338>**NOTE** 339>This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8). 340 341**System capability**: SystemCapability.Communication.NetStack 342 343**Parameters** 344 345| Name | Type | Mandatory| Description | 346| -------- | ----------------------- | ---- | --------------------------------- | 347| type | string | Yes | Event type. The value is **headerReceive**.| 348| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. | 349 350**Example** 351 352```js 353httpRequest.on('headerReceive', (data) => { 354 console.info('error:' + JSON.stringify(data)); 355}); 356``` 357 358### off('headerReceive') 359 360off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void 361 362Unregisters the observer for HTTP Response Header events. 363 364>**NOTE** 365> 366>1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8). 367> 368>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. 369 370**System capability**: SystemCapability.Communication.NetStack 371 372**Parameters** 373 374| Name | Type | Mandatory| Description | 375| -------- | ----------------------- | ---- | ------------------------------------- | 376| type | string | Yes | Event type. The value is **headerReceive**.| 377| callback | AsyncCallback\<Object\> | No | Callback used to return the result. | 378 379**Example** 380 381```js 382httpRequest.off('headerReceive'); 383``` 384 385### on('headersReceive')<sup>8+</sup> 386 387on(type: 'headersReceive', callback: Callback\<Object\>): void 388 389Registers an observer for HTTP Response Header events. 390 391**System capability**: SystemCapability.Communication.NetStack 392 393**Parameters** 394 395| Name | Type | Mandatory| Description | 396| -------- | ------------------ | ---- | ---------------------------------- | 397| type | string | Yes | Event type. The value is **headersReceive**.| 398| callback | Callback\<Object\> | Yes | Callback used to return the result. | 399 400**Example** 401 402```js 403httpRequest.on('headersReceive', (header) => { 404 console.info('header: ' + JSON.stringify(header)); 405}); 406``` 407 408### off('headersReceive')<sup>8+</sup> 409 410off(type: 'headersReceive', callback?: Callback\<Object\>): void 411 412Unregisters the observer for HTTP Response Header events. 413 414>**NOTE** 415>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. 416 417**System capability**: SystemCapability.Communication.NetStack 418 419**Parameters** 420 421| Name | Type | Mandatory| Description | 422| -------- | ------------------ | ---- | -------------------------------------- | 423| type | string | Yes | Event type. The value is **headersReceive**.| 424| callback | Callback\<Object\> | No | Callback used to return the result. | 425 426**Example** 427 428```js 429httpRequest.off('headersReceive'); 430``` 431 432### once('headersReceive')<sup>8+</sup> 433 434once(type: 'headersReceive', callback: Callback\<Object\>): void 435 436Registers 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. 437 438**System capability**: SystemCapability.Communication.NetStack 439 440**Parameters** 441 442| Name | Type | Mandatory| Description | 443| -------- | ------------------ | ---- | ---------------------------------- | 444| type | string | Yes | Event type. The value is **headersReceive**.| 445| callback | Callback\<Object\> | Yes | Callback used to return the result. | 446 447**Example** 448 449```js 450httpRequest.once('headersReceive', (header) => { 451 console.info('header: ' + JSON.stringify(header)); 452}); 453``` 454 455## HttpRequestOptions 456 457Specifies the type and value range of the optional parameters in the HTTP request. 458 459**System capability**: SystemCapability.Communication.NetStack 460 461| Name | Type | Mandatory| Description | 462| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 463| method | [RequestMethod](#requestmethod) | No | Request method. | 464| extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>6+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>6+</sup> | 465| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the return data. If this parameter is set, the system returns the specified type of data preferentially.| 466| usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. | 467| priority<sup>9+</sup> | number | No | Priority. The value range is \[1,1000]. The default value is **1**. | 468| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | 469| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | 470| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | 471| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. | 472 473## RequestMethod 474 475Defines an HTTP request method. 476 477**System capability**: SystemCapability.Communication.NetStack 478 479| Name | Value | Description | 480| :------ | ------- | :------------------ | 481| OPTIONS | "OPTIONS" | OPTIONS method.| 482| GET | "GET" | GET method. | 483| HEAD | "HEAD" | HEAD method. | 484| POST | "POST" | POST method. | 485| PUT | "PUT" | PUT method. | 486| DELETE | "DELETE" | DELETE method. | 487| TRACE | "TRACE" | TRACE method. | 488| CONNECT | "CONNECT" | CONNECT method.| 489 490## ResponseCode 491 492Enumerates the response codes for an HTTP request. 493 494**System capability**: SystemCapability.Communication.NetStack 495 496| Name | Value | Description | 497| ----------------- | ---- | ------------------------------------------------------------ | 498| OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. | 499| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | 500| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | 501| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | 502| 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. | 503| RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. | 504| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | 505| MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. | 506| 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.| 507| MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. | 508| SEE_OTHER | 303 | "See Other." The response to the request can be found under a different URI. | 509| NOT_MODIFIED | 304 | "Not Modified." The client has performed a conditional GET request and access is allowed, but the content has not been modified. | 510| USE_PROXY | 305 | "Use Proxy." The requested resource can only be accessed through the proxy. | 511| BAD_REQUEST | 400 | "Bad Request." The request could not be understood by the server due to incorrect syntax. | 512| UNAUTHORIZED | 401 | "Unauthorized." The request requires user authentication. | 513| PAYMENT_REQUIRED | 402 | "Payment Required." This code is reserved for future use. | 514| FORBIDDEN | 403 | "Forbidden." The server understands the request but refuses to process it. | 515| NOT_FOUND | 404 | "Not Found." The server does not find anything matching the Request-URI. | 516| BAD_METHOD | 405 | "Method Not Allowed." The method specified in the request is not allowed for the resource identified by the Request-URI. | 517| NOT_ACCEPTABLE | 406 | "Not Acceptable." The server cannot fulfill the request according to the content characteristics of the request. | 518| PROXY_AUTH | 407 | "Proxy Authentication Required." The request requires user authentication with the proxy. | 519| CLIENT_TIMEOUT | 408 | "Request Timeout." The client fails to generate a request within the timeout period. | 520| 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. | 521| GONE | 410 | "Gone." The requested resource has been deleted permanently and is no longer available. | 522| LENGTH_REQUIRED | 411 | "Length Required." The server refuses to process the request without a defined Content-Length. | 523| PRECON_FAILED | 412 | "Precondition Failed." The precondition in the request is incorrect. | 524| 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. | 525| REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. | 526| UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. | 527| INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. | 528| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | 529| BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.| 530| UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. | 531| 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. | 532| VERSION | 505 | "HTTP Version Not Supported." The server does not support the HTTP protocol version used in the request. | 533 534## HttpResponse 535 536Defines the response to an HTTP request. 537 538**System capability**: SystemCapability.Communication.NetStack 539 540| Name | Type | Mandatory| Description | 541| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 542| result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string| 543| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. | 544| 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**.| 545| 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'];| 546| cookies<sup>8+</sup> | string | Yes | Cookies returned by the server. | 547 548## http.createHttpResponseCache<sup>9+</sup> 549 550createHttpResponseCache(cacheSize?: number): HttpResponseCache 551 552Creates a default object to store responses to HTTP access requests. 553 554**System capability**: SystemCapability.Communication.NetStack 555 556**Parameters** 557 558| Name | Type | Mandatory| Description | 559| -------- | --------------------------------------- | ---- | ---------- | 560| cacheSize | number | No| Cache size. The maximum value is 10\*1024\*1024 (10 MB). By default, the maximum value is used.| 561 562**Return value** 563 564| Type | Description | 565| :---------- | :----------------------------------------------------------- | 566| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.| 567 568**Example** 569 570```js 571import http from '@ohos.net.http'; 572let httpResponseCache = http.createHttpResponseCache(); 573``` 574 575## HttpResponseCache<sup>9+</sup> 576 577Defines 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. 578 579### flush<sup>9+</sup> 580 581flush(callback: AsyncCallback\<void\>): void 582 583Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses an asynchronous callback to return the result. 584 585**System capability**: SystemCapability.Communication.NetStack 586 587**Parameters** 588 589| Name | Type | Mandatory| Description | 590| -------- | --------------------------------------- | ---- | ---------- | 591| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| 592 593**Example** 594 595```js 596httpResponseCache.flush(err => { 597 if (err) { 598 console.info('flush fail'); 599 return; 600 } 601 console.info('flush success'); 602}); 603``` 604 605### flush<sup>9+</sup> 606 607flush(): Promise\<void\> 608 609Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses a promise to return the result. 610 611**System capability**: SystemCapability.Communication.NetStack 612 613**Return value** 614 615| Type | Description | 616| --------------------------------- | ------------------------------------- | 617| Promise\<void\> | Promise used to return the result.| 618 619**Example** 620 621```js 622httpResponseCache.flush().then(() => { 623 console.info('flush success'); 624}).catch(err => { 625 console.info('flush fail'); 626}); 627``` 628 629### delete<sup>9+</sup> 630 631delete(callback: AsyncCallback\<void\>): void 632 633Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result. 634 635**System capability**: SystemCapability.Communication.NetStack 636 637**Parameters** 638 639| Name | Type | Mandatory| Description | 640| -------- | --------------------------------------- | ---- | ---------- | 641| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| 642 643**Example** 644 645```js 646httpResponseCache.delete(err => { 647 if (err) { 648 console.info('delete fail'); 649 return; 650 } 651 console.info('delete success'); 652}); 653``` 654### delete<sup>9+</sup> 655 656delete(): Promise\<void\> 657 658Disables the cache and deletes the data in it. This API uses a promise to return the result. 659 660**System capability**: SystemCapability.Communication.NetStack 661 662**Return value** 663 664| Type | Description | 665| --------------------------------- | ------------------------------------- | 666| Promise\<void\> | Promise used to return the result.| 667 668**Example** 669 670```js 671httpResponseCache.delete().then(() => { 672 console.info('delete success'); 673}).catch(err => { 674 console.info('delete fail'); 675}); 676``` 677 678## HttpDataType<sup>9+</sup> 679 680Enumerates HTTP data types. 681 682**System capability**: SystemCapability.Communication.NetStack 683 684| Name| Value| Description | 685| ------------------ | -- | ----------- | 686| STRING | 0 | String type.| 687| OBJECT | 1 | Object type. | 688| ARRAY_BUFFER | 2 | Binary array type.| 689 690## HttpProtocol<sup>9+</sup> 691 692Enumerates HTTP protocol versions. 693 694**System capability**: SystemCapability.Communication.NetStack 695 696| Name | Description | 697| :-------- | :----------- | 698| HTTP1_1 | HTTP1.1 | 699| HTTP2 | HTTP2 | 700