js-apis-http.md 28.5 KB
Newer Older
S
shawn_he 已提交
1
# @ohos.net.http (Data Request)
S
shawn_he 已提交
2

S
shawn_he 已提交
3
The **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**.
S
shawn_he 已提交
4

S
shawn_he 已提交
5 6
> **NOTE**<br>
> 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.
S
shawn_he 已提交
7 8 9

## Modules to Import

S
shawn_he 已提交
10
```js
S
shawn_he 已提交
11 12 13
import http from '@ohos.net.http';
```

S
shawn_he 已提交
14
## Example
S
shawn_he 已提交
15

S
shawn_he 已提交
16
```js
S
shawn_he 已提交
17 18
import http from '@ohos.net.http';

S
shawn_he 已提交
19
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
S
shawn_he 已提交
20
let httpRequest = http.createHttp();
S
shawn_he 已提交
21
// 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.
S
shawn_he 已提交
22
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
S
shawn_he 已提交
23 24
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
S
shawn_he 已提交
25 26
});
httpRequest.request(
S
shawn_he 已提交
27
    // Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL.
S
shawn_he 已提交
28 29
    "EXAMPLE_URL",
    {
S
shawn_he 已提交
30
        method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
S
shawn_he 已提交
31
        // You can add header fields based on service requirements.
S
shawn_he 已提交
32 33 34
        header: {
            'Content-Type': 'application/json'
        },
S
shawn_he 已提交
35
        // This field is used to transfer data when the POST request is used.
S
shawn_he 已提交
36 37 38
        extraData: {
            "data": "data to send",
        },
S
shawn_he 已提交
39 40 41 42
        expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
        usingCache: true, // Optional. The default value is true.
        priority: 1, // Optional. The default value is 1.
        connectTimeout: 60000 // Optional. The default value is 60000, in ms.
S
shawn_he 已提交
43
        readTimeout: 60000, // Optional. The default value is 60000, in ms.
S
shawn_he 已提交
44
        usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
S
shawn_he 已提交
45
    }, (err, data) => {
S
shawn_he 已提交
46
        if (!err) {
S
shawn_he 已提交
47
            // data.result carries the HTTP response. Parse the response based on service requirements.
S
shawn_he 已提交
48 49
            console.info('Result:' + data.result);
            console.info('code:' + data.responseCode);
S
shawn_he 已提交
50
            // data.header carries the HTTP response header. Parse the content based on service requirements.
S
shawn_he 已提交
51
            console.info('header:' + JSON.stringify(data.header));
S
shawn_he 已提交
52 53
            console.info('cookies:' + data.cookies); // 8+
        } else {
S
shawn_he 已提交
54
            console.info('error:' + JSON.stringify(err));
S
shawn_he 已提交
55
            // Call the destroy() method to release resources after HttpRequest is complete.
S
shawn_he 已提交
56 57 58 59 60 61 62 63 64 65
            httpRequest.destroy();
        }
    }
);
```

## http.createHttp

createHttp\(\): HttpRequest

S
shawn_he 已提交
66
Creates 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.
S
shawn_he 已提交
67 68 69

**System capability**: SystemCapability.Communication.NetStack

S
shawn_he 已提交
70
**Return value**
S
shawn_he 已提交
71 72 73

| Type       | Description                                                        |
| :---------- | :----------------------------------------------------------- |
S
shawn_he 已提交
74
| HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.|
S
shawn_he 已提交
75 76 77

**Example**

S
shawn_he 已提交
78
```js
S
shawn_he 已提交
79 80 81 82 83 84
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```

## HttpRequest

S
shawn_he 已提交
85
Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
S
shawn_he 已提交
86 87 88 89 90 91 92

### request

request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void

Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. 

S
shawn_he 已提交
93
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
94 95 96 97 98

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

S
shawn_he 已提交
99 100 101
| Name  | Type                                          | Mandatory| Description                   |
| -------- | ---------------------------------------------- | ---- | ----------------------- |
| url      | string                                         | Yes  | URL for initiating an HTTP request.|
S
shawn_he 已提交
102 103 104 105
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes  | Callback used to return the result.             |

**Example**

S
shawn_he 已提交
106
```js
S
shawn_he 已提交
107
httpRequest.request("EXAMPLE_URL", (err, data) => {
S
shawn_he 已提交
108 109 110 111 112 113 114 115
    if (!err) {
        console.info('Result:' + data.result);
        console.info('code:' + data.responseCode);
        console.info('header:' + JSON.stringify(data.header));
        console.info('cookies:' + data.cookies); // 8+
    } else {
        console.info('error:' + JSON.stringify(err));
    }
S
shawn_he 已提交
116 117 118 119 120 121 122 123 124
});
```

### request

request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpResponse\>\):void

Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
125
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                          | Mandatory| Description                                           |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url      | string                                         | Yes  | URL for initiating an HTTP request.                        |
| options  | HttpRequestOptions                             | Yes  | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes  | Callback used to return the result.                                     |

**Example**

S
shawn_he 已提交
139
```js
S
shawn_he 已提交
140 141
httpRequest.request("EXAMPLE_URL",
{
S
shawn_he 已提交
142
    method: http.RequestMethod.GET,
S
shawn_he 已提交
143 144 145 146 147 148 149 150 151
    header: {
        'Content-Type': 'application/json'
    },
    readTimeout: 60000,
    connectTimeout: 60000
}, (err, data) => {
    if (!err) {
        console.info('Result:' + data.result);
        console.info('code:' + data.responseCode);
S
shawn_he 已提交
152
        console.info('header:' + JSON.stringify(data.header));
S
shawn_he 已提交
153 154 155 156
        console.info('cookies:' + data.cookies); // 8+
        console.info('header.Content-Type:' + data.header['Content-Type']);
        console.info('header.Status-Line:' + data.header['Status-Line']);
    } else {
S
shawn_he 已提交
157
        console.info('error:' + JSON.stringify(err));
S
shawn_he 已提交
158
    }
S
shawn_he 已提交
159 160 161 162 163 164 165 166 167
});
```

### request

request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>

Initiates an HTTP request to a given URL. This API uses a promise to return the result. 

S
shawn_he 已提交
168
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
169 170 171 172 173

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

S
shawn_he 已提交
174 175 176
| Name | Type              | Mandatory| Description                                           |
| ------- | ------------------ | ---- | ----------------------------------------------- |
| url     | string             | Yes  | URL for initiating an HTTP request.                        |
S
shawn_he 已提交
177
| options | HttpRequestOptions | No  | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
S
shawn_he 已提交
178

S
shawn_he 已提交
179
**Return value**
S
shawn_he 已提交
180

S
shawn_he 已提交
181 182
| Type                                  | Description                             |
| :------------------------------------- | :-------------------------------- |
S
shawn_he 已提交
183 184 185 186 187
| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.|


**Example**

S
shawn_he 已提交
188
```js
S
shawn_he 已提交
189
let promise = httpRequest.request("EXAMPLE_URL", {
S
shawn_he 已提交
190
    method: http.RequestMethod.GET,
S
shawn_he 已提交
191 192 193 194 195
    connectTimeout: 60000,
    readTimeout: 60000,
    header: {
        'Content-Type': 'application/json'
    }
S
shawn_he 已提交
196
});
S
shawn_he 已提交
197 198 199 200 201 202 203
promise.then((data) => {
    console.info('Result:' + data.result);
    console.info('code:' + data.responseCode);
    console.info('header:' + JSON.stringify(data.header));
    console.info('cookies:' + data.cookies); // 8+
    console.info('header.Content-Type:' + data.header['Content-Type']);
    console.info('header.Status-Line:' + data.header['Status-Line']);
S
shawn_he 已提交
204
}).catch((err) => {
S
shawn_he 已提交
205
    console.info('error:' + JSON.stringify(err));
S
shawn_he 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218
});
```

### destroy

destroy\(\): void

Destroys an HTTP request.

**System capability**: SystemCapability.Communication.NetStack

**Example**

S
shawn_he 已提交
219
```js
S
shawn_he 已提交
220 221 222 223 224 225 226 227 228
httpRequest.destroy();
```

### on\('headerReceive'\)

on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void

Registers an observer for HTTP Response Header events.

S
shawn_he 已提交
229
>**NOTE**
S
shawn_he 已提交
230
>This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead.
S
shawn_he 已提交
231 232 233 234 235 236 237 238 239 240 241 242

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                   | Mandatory| Description                             |
| -------- | ----------------------- | ---- | --------------------------------- |
| type     | string                  | Yes  | Event type. The value is **headerReceive**.|
| callback | AsyncCallback\<Object\> | Yes  | Callback used to return the result.                       |

**Example**

S
shawn_he 已提交
243
```js
S
shawn_he 已提交
244
httpRequest.on('headerReceive', (err, data) => {
S
shawn_he 已提交
245 246 247 248 249
    if (!err) {
        console.info('header: ' + JSON.stringify(data));
    } else {
        console.info('error:' + JSON.stringify(err));
    }
S
shawn_he 已提交
250 251 252 253 254 255 256 257 258
});
```

### off\('headerReceive'\)

off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void

Unregisters the observer for HTTP Response Header events.

S
shawn_he 已提交
259
>**NOTE**
S
shawn_he 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
>
>1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead.
>
>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.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                   | Mandatory| Description                                 |
| -------- | ----------------------- | ---- | ------------------------------------- |
| type     | string                  | Yes  | Event type. The value is **headerReceive**.|
| callback | AsyncCallback\<Object\> | No  | Callback used to return the result.                           |

**Example**

S
shawn_he 已提交
276
```js
S
shawn_he 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
httpRequest.off('headerReceive');
```

### on\('headersReceive'\)<sup>8+</sup>

on\(type: 'headersReceive', callback: Callback<Object\>\): void

Registers an observer for HTTP Response Header events.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type              | Mandatory| Description                              |
| -------- | ------------------ | ---- | ---------------------------------- |
| type     | string             | Yes  | Event type. The value is **headersReceive**.|
| callback | Callback\<Object\> | Yes  | Callback used to return the result.                        |

**Example**

S
shawn_he 已提交
297
```js
S
shawn_he 已提交
298 299
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
S
shawn_he 已提交
300 301 302 303 304 305 306 307 308
});
```

### off\('headersReceive'\)<sup>8+</sup>

off\(type: 'headersReceive', callback?: Callback<Object\>\): void

Unregisters the observer for HTTP Response Header events.

S
shawn_he 已提交
309
>**NOTE**
S
shawn_he 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322
>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.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type              | Mandatory| Description                                  |
| -------- | ------------------ | ---- | -------------------------------------- |
| type     | string             | Yes  | Event type. The value is **headersReceive**.|
| callback | Callback\<Object\> | No  | Callback used to return the result.                            |

**Example**

S
shawn_he 已提交
323
```js
S
shawn_he 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
httpRequest.off('headersReceive');
```

### once\('headersReceive'\)<sup>8+</sup>

once\(type: 'headersReceive', callback: Callback<Object\>\): void

Registers 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.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type              | Mandatory| Description                              |
| -------- | ------------------ | ---- | ---------------------------------- |
| type     | string             | Yes  | Event type. The value is **headersReceive**.|
| callback | Callback\<Object\> | Yes  | Callback used to return the result.                        |

**Example**

S
shawn_he 已提交
344
```js
S
shawn_he 已提交
345 346
httpRequest.once('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
S
shawn_he 已提交
347 348 349 350 351 352 353 354 355
});
```

## HttpRequestOptions

Specifies the type and value range of the optional parameters in the HTTP request.

**System capability**: SystemCapability.Communication.NetStack

S
shawn_he 已提交
356 357 358
| Name        | Type                                         | Mandatory| Description                                                        |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method         | [RequestMethod](#requestmethod)               | No  | Request method.                                                  |
S
shawn_he 已提交
359 360 361 362
| 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> |
| 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.|
| usingCache<sup>9+</sup>      | boolean                         | No  | Whether to use the cache. The default value is **true**.  |
| priority<sup>9+</sup>        | number                          | No  | Priority. The value range is \[1,1000]. The default value is **1**.                          |
S
shawn_he 已提交
363 364 365
| header         | Object                                        | No  | HTTP request header. The default value is **{'Content-Type': 'application/json'}**.  |
| readTimeout    | number                                        | No  | Read timeout duration. The default value is **60000**, in ms.             |
| connectTimeout | number                                        | No  | Connection timeout interval. The default value is **60000**, in ms.             |
S
shawn_he 已提交
366
| usingProtocol<sup>9+</sup>   | [HttpProtocol](#httpprotocol9)   | No  | Protocol. The default value is automatically specified by the system.             |
S
shawn_he 已提交
367 368 369 370 371 372 373 374 375

## RequestMethod

Defines an HTTP request method.

**System capability**: SystemCapability.Communication.NetStack

| Name   | Value     | Description               |
| :------ | ------- | :------------------ |
S
shawn_he 已提交
376 377 378 379 380 381 382 383
| OPTIONS | "OPTIONS" | OPTIONS method.|
| GET     | "GET"     | GET method.    |
| HEAD    | "HEAD"    | HEAD method.   |
| POST    | "POST"    | POST method.   |
| PUT     | "PUT"     | PUT method.    |
| DELETE  | "DELETE"  | DELETE method. |
| TRACE   | "TRACE"   | TRACE method.  |
| CONNECT | "CONNECT" | CONNECT method.|
S
shawn_he 已提交
384 385 386 387 388 389 390 391 392

## ResponseCode

Enumerates the response codes for an HTTP request.

**System capability**: SystemCapability.Communication.NetStack

| Name             | Value  | Description                                                        |
| ----------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
393
| OK                | 200  | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests.                           |
S
shawn_he 已提交
394
| CREATED           | 201  | "Created." The request has been successfully sent and a new resource is created.                          |
S
shawn_he 已提交
395
| ACCEPTED          | 202  | "Accepted." The request has been accepted, but the processing has not been completed.                        |
S
shawn_he 已提交
396 397 398
| NOT_AUTHORITATIVE | 203  | "Non-Authoritative Information." The request is successful.                                      |
| 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.                      |
| RESET             | 205  | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content.                                                  |
S
shawn_he 已提交
399
| PARTIAL           | 206  | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource.                     |
S
shawn_he 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
| MULT_CHOICE       | 300  | "Multiple Choices." The requested resource corresponds to any one of a set of representations.                                                  |
| 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.|
| MOVED_TEMP        | 302  | "Moved Temporarily." The requested resource is moved temporarily to a different URI.                                                  |
| SEE_OTHER         | 303  | "See Other." The response to the request can be found under a different URI.                                              |
| NOT_MODIFIED      | 304  | "Not Modified." The client has performed a conditional GET request and access is allowed, but the content has not been modified.                                                    |
| USE_PROXY         | 305  | "Use Proxy." The requested resource can only be accessed through the proxy.                                                  |
| BAD_REQUEST       | 400  | "Bad Request." The request could not be understood by the server due to incorrect syntax.                       |
| UNAUTHORIZED      | 401  | "Unauthorized." The request requires user authentication.                                    |
| PAYMENT_REQUIRED  | 402  | "Payment Required." This code is reserved for future use.                                            |
| FORBIDDEN         | 403  | "Forbidden." The server understands the request but refuses to process it.            |
| NOT_FOUND         | 404  | "Not Found." The server does not find anything matching the Request-URI.                |
| BAD_METHOD        | 405  | "Method Not Allowed." The method specified in the request is not allowed for the resource identified by the Request-URI.                                  |
| NOT_ACCEPTABLE    | 406  | "Not Acceptable." The server cannot fulfill the request according to the content characteristics of the request.                 |
| PROXY_AUTH        | 407  | "Proxy Authentication Required." The request requires user authentication with the proxy.                                    |
| CLIENT_TIMEOUT    | 408  | "Request Timeout." The client fails to generate a request within the timeout period.                                        |
| 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. |
| GONE              | 410  | "Gone." The requested resource has been deleted permanently and is no longer available.                                 |
| LENGTH_REQUIRED   | 411  | "Length Required." The server refuses to process the request without a defined Content-Length.    |
| PRECON_FAILED     | 412  | "Precondition Failed." The precondition in the request is incorrect.                              |
| 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.           |
| REQ_TOO_LONG      | 414  | "Request-URI Too Long." The Request-URI is too long for the server to process.             |
| UNSUPPORTED_TYPE  | 415  | "Unsupported Media Type." The server is unable to process the media format in the request.                                   |
| INTERNAL_ERROR    | 500  | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request.                              |
S
shawn_he 已提交
423
| NOT_IMPLEMENTED   | 501  | "Not Implemented." The server does not support the function required to fulfill the request.                      |
S
shawn_he 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436
| BAD_GATEWAY       | 502  | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.|
| UNAVAILABLE       | 503  | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance.      |
| 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.        |
| VERSION           | 505  | "HTTP Version Not Supported." The server does not support the HTTP protocol version used in the request.                                 |

## HttpResponse

Defines the response to an HTTP request.

**System capability**: SystemCapability.Communication.NetStack

| Name              | Type                                        | Mandatory| Description                                                        |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
437
| 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|
S
shawn_he 已提交
438
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9)             | Yes  | Type of the return value.                          |
S
shawn_he 已提交
439
| 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**. For details, see [Error Codes](#error-codes).|
S
shawn_he 已提交
440 441
| 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'];|
| cookies<sup>8+</sup> | Array\<string\>                              | Yes  | Cookies returned by the server.                                      |
S
shawn_he 已提交
442

S
shawn_he 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
## http.createHttpResponseCache<sup>9+</sup>

createHttpResponseCache(cacheSize?: number): HttpResponseCache

Creates a default object to store responses to HTTP access requests.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                   | Mandatory| Description      |
| -------- | --------------------------------------- | ---- | ---------- |
| cacheSize | number | No| Cache size. The maximum value is 10\*1024\*1024 (10 MB). By default, the maximum value is used.|

**Return value**

| Type       | Description                                                        |
| :---------- | :----------------------------------------------------------- |
| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.|

**Example**

```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
```

## HttpResponseCache<sup>9+</sup>

Defines an object that stores the response to an HTTP request.

### flush<sup>9+</sup>

flush(callback: AsyncCallback\<void>): void

Flushes 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.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                   | Mandatory| Description      |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|

**Example**

```js
httpResponseCache.flush(err => {
  if (err) {
    console.log('flush fail');
    return;
  }
  console.log('flush success');
});
```

### flush<sup>9+</sup>

flush(): Promise\<void>

Flushes 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.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

| Type                             | Description                                 |
| --------------------------------- | ------------------------------------- |
| Promise\<void>> | Promise used to return the result.|

**Example**

```js
httpResponseCache.flush().then(() => {
  console.log('flush success');
}).catch(err => {
  console.log('flush fail');
});
```

### delete<sup>9+</sup>

delete(callback: AsyncCallback\<void>): void

Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                   | Mandatory| Description      |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|

**Example**

```js
httpResponseCache.delete(err => {
  if (err) {
    console.log('delete fail');
    return;
  }
  console.log('delete success');
});
```
### delete<sup>9+</sup>

delete(): Promise\<void>

Disables the cache and deletes the data in it. This API uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

| Type                             | Description                                 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> |  Promise used to return the result.|

**Example**

```js
httpResponseCache.delete().then(() => {
  console.log('delete success');
}).catch(err => {
  console.log('delete fail');
});
```

S
shawn_he 已提交
573 574 575 576
## Error Codes

| Error Code| Description                                                        |
| ------ | ------------------------------------------------------------ |
S
shawn_he 已提交
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
| -1     | Incorrect parameter. Check whether the number and type of parameters are correct.                          |
| 3      | Incorrect URL format. Check whether the format and syntax of the URL are correct.                        |
| 4      | Built-in request function, protocol, or option not found during build. If a function or option is not enabled or explicitly disabled, you need to rebuild a libcurl in order to access its functions.             |
| 5      | Unable to resolve the proxy because of a failure to resolve the specified proxy server. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 6      | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available.      |
| 7      | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host.                                   |

## HttpDataType<sup>9+</sup>

Enumerates HTTP data types.

**System capability**: SystemCapability.Communication.NetStack

| Name| Value| Description    |
| ------------------ | -- | ----------- |
| STRING              | 0 | String type.|
| OBJECT              | 1 | Object type.   |
| ARRAY_BUFFER        | 2 | Binary array type.|

## HttpProtocol<sup>9+</sup>

Enumerates HTTP protocol versions.

**System capability**: SystemCapability.Communication.NetStack

| Name | Description    |
| :-------- | :----------- |
| HTTP1_1   |  HTTP1.1 |
| HTTP2     |  HTTP2   |