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