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