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

S
shawn_he 已提交
3
This 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 7 8
>**NOTE**
>
>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 已提交
9 10 11

## Modules to Import

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

S
shawn_he 已提交
16
## Example
S
shawn_he 已提交
17

S
shawn_he 已提交
18
```js
S
shawn_he 已提交
19
// Import the http namespace.
S
shawn_he 已提交
20 21
import http from '@ohos.net.http';

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

## http.createHttp

S
shawn_he 已提交
70
createHttp(): HttpRequest
S
shawn_he 已提交
71

S
shawn_he 已提交
72
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 已提交
73 74 75

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

S
shawn_he 已提交
76
**Return value**
S
shawn_he 已提交
77 78

| Type       | Description                                                        |
S
shawn_he 已提交
79
| :---------- | :----------------------------------------------------------- |
S
shawn_he 已提交
80
| HttpRequest | An **HttpRequest** object, which contains the **request**, **request2**, **destroy**, **on**, or **off** method.|
S
shawn_he 已提交
81 82 83

**Example**

S
shawn_he 已提交
84
```js
S
shawn_he 已提交
85 86 87 88 89 90
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```

## HttpRequest

S
shawn_he 已提交
91
Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp()](#httpcreatehttp) to create an **HttpRequestTask** object.
S
shawn_he 已提交
92 93 94

### request

S
shawn_he 已提交
95
request(url: string, callback: AsyncCallback\<HttpResponse\>):void
S
shawn_he 已提交
96 97 98

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

S
shawn_he 已提交
99 100 101
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.

S
shawn_he 已提交
102
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
103 104 105 106 107

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

**Parameters**

S
shawn_he 已提交
108 109 110
| Name  | Type                                          | Mandatory| Description                   |
| -------- | ---------------------------------------------- | ---- | ----------------------- |
| url      | string                                         | Yes  | URL for initiating an HTTP request.|
S
shawn_he 已提交
111 112
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes  | Callback used to return the result.             |

S
shawn_he 已提交
113 114
**Error codes**

S
shawn_he 已提交
115
| Code  | Error Message                                                 |
S
shawn_he 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128
|---------|-------------------------------------------------------|
| 401     | Parameter error.                                      |
| 201     | Permission denied.                                    |
| 2300003 | URL using bad/illegal format or missing URL.          |
| 2300007 | Couldn't connect to server.                           |
| 2300028 | Timeout was reached.                                  |
| 2300052 | Server returned nothing (no headers, no data).        |
| 2300999 | Unknown Other Error.                                  |

>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> 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).

S
shawn_he 已提交
129 130
**Example**

S
shawn_he 已提交
131
```js
S
shawn_he 已提交
132
httpRequest.request("EXAMPLE_URL", (err, data) => {
S
shawn_he 已提交
133 134 135 136 137 138 139 140
    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 已提交
141 142 143 144 145
});
```

### request

S
shawn_he 已提交
146
request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpResponse\>):void
S
shawn_he 已提交
147 148 149

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

S
shawn_he 已提交
150 151 152
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.

S
shawn_he 已提交
153
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
154 155 156 157 158 159 160 161 162 163 164

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

S
shawn_he 已提交
165 166
**Error codes**

S
shawn_he 已提交
167
| Code  | Error Message                                                 |
S
shawn_he 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
|---------|-------------------------------------------------------|
| 401     | Parameter error.                                      |
| 201     | Permission denied.                                    |
| 2300001 | Unsupported protocol.                                 |
| 2300003 | URL using bad/illegal format or missing URL.          |
| 2300005 | Couldn't resolve proxy name.                          |
| 2300006 | Couldn't resolve host name.                           |
| 2300007 | Couldn't connect to server.                           |
| 2300008 | Weird server reply.                                   |
| 2300009 | Access denied to remote resource.                     |
| 2300016 | Error in the HTTP2 framing layer.                     |
| 2300018 | Transferred a partial file.                           |
| 2300023 | Failed writing received data to disk/application.     |
| 2300025 | Upload failed.                                        |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory.                                        |
| 2300028 | Timeout was reached.                                  |
| 2300047 | Number of redirects hit maximum amount.               |
| 2300052 | Server returned nothing (no headers, no data).        |
| 2300055 | Failed sending data to the peer.                      |
| 2300056 | Failure when receiving data from the peer.            |
| 2300058 | Problem with the local SSL certificate.               |
| 2300059 | Couldn't use specified SSL cipher.                    |
| 2300060 | SSL peer certificate or SSH remote key was not OK.    |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded.                           |
| 2300070 | Disk full or allocation exceeded.                     |
| 2300073 | Remote file already exists.                           |
| 2300077 | Problem with the SSL CA cert (path? access rights?).  |
| 2300078 | Remote file not found.                                |
| 2300094 | An authentication function returned an error.         |
| 2300999 | Unknown Other Error.                                  |

>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> 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).

S
shawn_he 已提交
205 206
**Example**

S
shawn_he 已提交
207
```js
S
shawn_he 已提交
208 209
httpRequest.request("EXAMPLE_URL",
{
S
shawn_he 已提交
210
    method: http.RequestMethod.GET,
S
shawn_he 已提交
211 212 213 214 215 216 217 218 219
    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 已提交
220
        console.info('header:' + JSON.stringify(data.header));
S
shawn_he 已提交
221 222 223 224
        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 已提交
225
        console.info('error:' + JSON.stringify(err));
S
shawn_he 已提交
226
    }
S
shawn_he 已提交
227 228 229 230 231
});
```

### request

S
shawn_he 已提交
232
request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
S
shawn_he 已提交
233

S
shawn_he 已提交
234
Initiates an HTTP request to a given URL. This API uses a promise to return the result. 
S
shawn_he 已提交
235

S
shawn_he 已提交
236 237 238
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.

S
shawn_he 已提交
239
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
240 241 242 243 244

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

**Parameters**

S
shawn_he 已提交
245 246 247
| Name | Type              | Mandatory| Description                                           |
| ------- | ------------------ | ---- | ----------------------------------------------- |
| url     | string             | Yes  | URL for initiating an HTTP request.                        |
S
shawn_he 已提交
248
| options | HttpRequestOptions | No  | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
S
shawn_he 已提交
249

S
shawn_he 已提交
250
**Return value**
S
shawn_he 已提交
251

S
shawn_he 已提交
252
| Type                                  | Description                             |
S
shawn_he 已提交
253
| :------------------------------------- | :-------------------------------- |
S
shawn_he 已提交
254 255
| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.|

S
shawn_he 已提交
256 257
**Error codes**

S
shawn_he 已提交
258
| Code  | Error Message                                                 |
S
shawn_he 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
|---------|-------------------------------------------------------|
| 401     | Parameter error.                                      |
| 201     | Permission denied.                                    |
| 2300001 | Unsupported protocol.                                 |
| 2300003 | URL using bad/illegal format or missing URL.          |
| 2300005 | Couldn't resolve proxy name.                          |
| 2300006 | Couldn't resolve host name.                           |
| 2300007 | Couldn't connect to server.                           |
| 2300008 | Weird server reply.                                   |
| 2300009 | Access denied to remote resource.                     |
| 2300016 | Error in the HTTP2 framing layer.                     |
| 2300018 | Transferred a partial file.                           |
| 2300023 | Failed writing received data to disk/application.     |
| 2300025 | Upload failed.                                        |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory.                                        |
| 2300028 | Timeout was reached.                                  |
| 2300047 | Number of redirects hit maximum amount.               |
| 2300052 | Server returned nothing (no headers, no data).        |
| 2300055 | Failed sending data to the peer.                      |
| 2300056 | Failure when receiving data from the peer.            |
| 2300058 | Problem with the local SSL certificate.               |
| 2300059 | Couldn't use specified SSL cipher.                    |
| 2300060 | SSL peer certificate or SSH remote key was not OK.    |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded.                           |
| 2300070 | Disk full or allocation exceeded.                     |
| 2300073 | Remote file already exists.                           |
| 2300077 | Problem with the SSL CA cert (path? access rights?).  |
| 2300078 | Remote file not found.                                |
| 2300094 | An authentication function returned an error.         |
| 2300999 | Unknown Other Error.                                  |

>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> 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).
S
shawn_he 已提交
295 296 297

**Example**

S
shawn_he 已提交
298
```js
S
shawn_he 已提交
299
let promise = httpRequest.request("EXAMPLE_URL", {
S
shawn_he 已提交
300
    method: http.RequestMethod.GET,
S
shawn_he 已提交
301 302 303 304 305
    connectTimeout: 60000,
    readTimeout: 60000,
    header: {
        'Content-Type': 'application/json'
    }
S
shawn_he 已提交
306
});
S
shawn_he 已提交
307 308 309 310 311 312 313
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 已提交
314
}).catch((err) => {
S
shawn_he 已提交
315
    console.info('error:' + JSON.stringify(err));
S
shawn_he 已提交
316 317 318 319 320
});
```

### destroy

S
shawn_he 已提交
321
destroy(): void
S
shawn_he 已提交
322 323 324 325 326 327 328

Destroys an HTTP request.

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

**Example**

S
shawn_he 已提交
329
```js
S
shawn_he 已提交
330 331 332
httpRequest.destroy();
```

S
shawn_he 已提交
333 334
### request2<sup>10+</sup>

S
shawn_he 已提交
335
request2(url: string, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.

**Required permissions**: ohos.permission.INTERNET

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

**Parameters**

| Name  | Type                                          | Mandatory| Description                                           |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url      | string                                         | Yes  | URL for initiating an HTTP request.                        |
| callback | AsyncCallback\<void\>                          | Yes  | Callback used to return the result.                                     |

**Error codes**

S
shawn_he 已提交
352
| Code  | Error Message                                                 |
S
shawn_he 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
|---------|-------------------------------------------------------|
| 401     | Parameter error.                                      |
| 201     | Permission denied.                                    |
| 2300003 | URL using bad/illegal format or missing URL.          |
| 2300007 | Couldn't connect to server.                           |
| 2300028 | Timeout was reached.                                  |
| 2300052 | Server returned nothing (no headers, no data).        |
| 2300999 | Unknown Other Error.                                  |

>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> 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).

**Example**

```js
httpRequest.request2("EXAMPLE_URL", (err) => {
    if (!err) {
S
shawn_he 已提交
371
        console.info("request2 OK!");
S
shawn_he 已提交
372 373 374 375 376 377 378 379
    } else {
        console.info("request2 ERROR : err = " + JSON.stringify(err));
    }
})
```

### request2<sup>10+</sup>

S
shawn_he 已提交
380
request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
381

S
shawn_he 已提交
382
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
S
shawn_he 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397

**Required permissions**: ohos.permission.INTERNET

**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\<void\>                          | Yes  | Callback used to return the result.                                     |

**Error codes**

S
shawn_he 已提交
398
| Code  | Error Message                                                 |
S
shawn_he 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
|---------|-------------------------------------------------------|
| 401     | Parameter error.                                      |
| 201     | Permission denied.                                    |
| 2300001 | Unsupported protocol.                                 |
| 2300003 | URL using bad/illegal format or missing URL.          |
| 2300005 | Couldn't resolve proxy name.                          |
| 2300006 | Couldn't resolve host name.                           |
| 2300007 | Couldn't connect to server.                           |
| 2300008 | Weird server reply.                                   |
| 2300009 | Access denied to remote resource.                     |
| 2300016 | Error in the HTTP2 framing layer.                     |
| 2300018 | Transferred a partial file.                           |
| 2300023 | Failed writing received data to disk/application.     |
| 2300025 | Upload failed.                                        |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory.                                        |
| 2300028 | Timeout was reached.                                  |
| 2300047 | Number of redirects hit maximum amount.               |
| 2300052 | Server returned nothing (no headers, no data).        |
| 2300055 | Failed sending data to the peer.                      |
| 2300056 | Failure when receiving data from the peer.            |
| 2300058 | Problem with the local SSL certificate.               |
| 2300059 | Couldn't use specified SSL cipher.                    |
| 2300060 | SSL peer certificate or SSH remote key was not OK.    |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded.                           |
| 2300070 | Disk full or allocation exceeded.                     |
| 2300073 | Remote file already exists.                           |
| 2300077 | Problem with the SSL CA cert (path? access rights?).  |
| 2300078 | Remote file not found.                                |
| 2300094 | An authentication function returned an error.         |
| 2300999 | Unknown Other Error.                                  |

>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> 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).

**Example**

```js
httpRequest.request2("EXAMPLE_URL",
{
    method: http.RequestMethod.GET,
    header: {
        'Content-Type': 'application/json'
    },
    readTimeout: 60000,
    connectTimeout: 60000
}, (err) => {
    if (!err) {
S
shawn_he 已提交
449
        console.info("request2 OK!");
S
shawn_he 已提交
450 451 452 453 454 455 456
    } else {
        console.info("request2 ERROR : err = " + JSON.stringify(err));
    }
})
```
### request2<sup>10+</sup>

S
shawn_he 已提交
457
request2(url: string, options? : HttpRequestOptions): Promise\<void\>
S
shawn_he 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response.

**Required permissions**: ohos.permission.INTERNET

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

**Parameters**

| Name | Type              | Mandatory| Description                                           |
| ------- | ------------------ | ---- | ----------------------------------------------- |
| url     | string             | Yes  | URL for initiating an HTTP request.                        |
| options | HttpRequestOptions | No  | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|

**Return value**

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

**Error codes**

S
shawn_he 已提交
480
| Code  | Error Message                                                 |
S
shawn_he 已提交
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
|---------|-------------------------------------------------------|
| 401     | Parameter error.                                      |
| 201     | Permission denied.                                    |
| 2300001 | Unsupported protocol.                                 |
| 2300003 | URL using bad/illegal format or missing URL.          |
| 2300005 | Couldn't resolve proxy name.                          |
| 2300006 | Couldn't resolve host name.                           |
| 2300007 | Couldn't connect to server.                           |
| 2300008 | Weird server reply.                                   |
| 2300009 | Access denied to remote resource.                     |
| 2300016 | Error in the HTTP2 framing layer.                     |
| 2300018 | Transferred a partial file.                           |
| 2300023 | Failed writing received data to disk/application.     |
| 2300025 | Upload failed.                                        |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory.                                        |
| 2300028 | Timeout was reached.                                  |
| 2300047 | Number of redirects hit maximum amount.               |
| 2300052 | Server returned nothing (no headers, no data).        |
| 2300055 | Failed sending data to the peer.                      |
| 2300056 | Failure when receiving data from the peer.            |
| 2300058 | Problem with the local SSL certificate.               |
| 2300059 | Couldn't use specified SSL cipher.                    |
| 2300060 | SSL peer certificate or SSH remote key was not OK.    |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded.                           |
| 2300070 | Disk full or allocation exceeded.                     |
| 2300073 | Remote file already exists.                           |
| 2300077 | Problem with the SSL CA cert (path? access rights?).  |
| 2300078 | Remote file not found.                                |
| 2300094 | An authentication function returned an error.         |
| 2300999 | Unknown Other Error.                                  |

>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
S
shawn_he 已提交
516
> 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).
S
shawn_he 已提交
517 518 519 520 521 522 523 524 525 526 527 528 529

**Example**

```js
let promise = httpRequest.request("EXAMPLE_URL", {
    method: http.RequestMethod.GET,
    connectTimeout: 60000,
    readTimeout: 60000,
    header: {
        'Content-Type': 'application/json'
    }
});
promise.then(() => {
S
shawn_he 已提交
530
    console.info("request2 OK!");
S
shawn_he 已提交
531 532 533 534 535
}).catch((err) => {
    console.info("request2 ERROR : err = " + JSON.stringify(err));
});
```

S
shawn_he 已提交
536
### on('headerReceive')
S
shawn_he 已提交
537

S
shawn_he 已提交
538
on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void
S
shawn_he 已提交
539 540 541

Registers an observer for HTTP Response Header events.

S
shawn_he 已提交
542
>**NOTE**
S
shawn_he 已提交
543
>This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8) instead.
S
shawn_he 已提交
544 545 546 547 548 549 550 551 552 553 554 555

**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 已提交
556
```js
S
shawn_he 已提交
557 558
httpRequest.on('headerReceive', (data) => {
    console.info('error:' + JSON.stringify(data));
S
shawn_he 已提交
559 560 561
});
```

S
shawn_he 已提交
562
### off('headerReceive')
S
shawn_he 已提交
563

S
shawn_he 已提交
564
off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void
S
shawn_he 已提交
565 566 567

Unregisters the observer for HTTP Response Header events.

S
shawn_he 已提交
568
>**NOTE**
S
shawn_he 已提交
569
>
S
shawn_he 已提交
570
>1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8) instead.
S
shawn_he 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584
>
>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 已提交
585
```js
S
shawn_he 已提交
586 587 588
httpRequest.off('headerReceive');
```

S
shawn_he 已提交
589
### on('headersReceive')<sup>8+</sup>
S
shawn_he 已提交
590

S
shawn_he 已提交
591
on(type: 'headersReceive', callback: Callback\<Object\>): void
S
shawn_he 已提交
592 593 594 595 596 597 598 599 600 601 602 603 604 605

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 已提交
606
```js
S
shawn_he 已提交
607 608
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
S
shawn_he 已提交
609 610 611
});
```

S
shawn_he 已提交
612
### off('headersReceive')<sup>8+</sup>
S
shawn_he 已提交
613

S
shawn_he 已提交
614
off(type: 'headersReceive', callback?: Callback\<Object\>): void
S
shawn_he 已提交
615 616 617

Unregisters the observer for HTTP Response Header events.

S
shawn_he 已提交
618
>**NOTE**
S
shawn_he 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631
>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 已提交
632
```js
S
shawn_he 已提交
633 634 635
httpRequest.off('headersReceive');
```

S
shawn_he 已提交
636
### once('headersReceive')<sup>8+</sup>
S
shawn_he 已提交
637

S
shawn_he 已提交
638
once(type: 'headersReceive', callback: Callback\<Object\>): void
S
shawn_he 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652

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 已提交
653
```js
S
shawn_he 已提交
654 655
httpRequest.once('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
S
shawn_he 已提交
656 657
});
```
S
shawn_he 已提交
658
### on('dataReceive')<sup>10+</sup>
S
shawn_he 已提交
659

S
shawn_he 已提交
660
on(type: 'dataReceive', callback: Callback\<ArrayBuffer\>): void
S
shawn_he 已提交
661 662

Registers an observer for events indicating receiving of HTTP streaming responses.
S
shawn_he 已提交
663

S
shawn_he 已提交
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
**System capability**: SystemCapability.Communication.NetStack

**Parameters**

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

**Example**

```js
httpRequest.on('dataReceive', (data) => {
    console.info('dataReceive length: ' + JSON.stringify(data.byteLength));
});
```

S
shawn_he 已提交
681
### off('dataReceive')<sup>10+</sup>
S
shawn_he 已提交
682

S
shawn_he 已提交
683
off(type: 'dataReceive', callback?: Callback\<ArrayBuffer\>): void
S
shawn_he 已提交
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

Unregisters the observer for events indicating receiving of HTTP streaming responses.

>**NOTE**
>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 **dataReceive**.|
| callback | Callback\<ArrayBuffer\> | No  | Callback used to return the result.                            |

**Example**

```js
httpRequest.off('dataReceive');
```

S
shawn_he 已提交
705
### on('dataEnd')<sup>10+</sup>
S
shawn_he 已提交
706

S
shawn_he 已提交
707
on(type: 'dataEnd', callback: Callback\<void\>): void
S
shawn_he 已提交
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727

Registers an observer for events indicating completion of receiving HTTP streaming responses.

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

**Parameters**

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

**Example**

```js
httpRequest.on('dataReceive', () => {
    console.info('Receive dataEnd! ');
});
```

S
shawn_he 已提交
728
### off('dataEnd')<sup>10+</sup>
S
shawn_he 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751

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

Unregisters the observer for events indicating completion of receiving HTTP streaming responses.

>**NOTE**
>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 **dataEnd**.|
| callback | Callback\<void\>   | No  | Callback used to return the result.                            |

**Example**

```js
httpRequest.off('dataEnd');
```

S
shawn_he 已提交
752
### on('dataProgress')<sup>10+</sup>
S
shawn_he 已提交
753

S
shawn_he 已提交
754
 on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void
S
shawn_he 已提交
755 756 757 758 759 760 761 762 763 764

Registers an observer for events indicating progress of receiving HTTP streaming responses.

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

**Parameters**

| Name  | Type                   | Mandatory| Description                             |
| -------- | ----------------------- | ---- | --------------------------------- |
| type     | string                  | Yes  | Event type. The value is **dataProgress**.|
S
shawn_he 已提交
765
| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\>   | Yes  | Callback used to return the result.<br>**receiveSize**: number of received bytes.<br>**totalSize**: total number of bytes to be received.|
S
shawn_he 已提交
766 767 768 769 770

**Example**

```js
httpRequest.on('dataProgress', (data) => {
S
shawn_he 已提交
771
    console.info('dataProgress:' + JSON.stringify(data));
S
shawn_he 已提交
772 773 774
});
```

S
shawn_he 已提交
775
### off('dataProgress')<sup>10+</sup>
S
shawn_he 已提交
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797

off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void

Unregisters the observer for events indicating progress of receiving HTTP streaming responses.

>**NOTE**
>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 **dataProgress**.|
| callback | Callback\<{ receiveSize: number, totalSize: number }\>   | No  | Callback used to return the result.                            |

**Example**

```js
httpRequest.off('dataProgress');
```
S
shawn_he 已提交
798 799 800 801 802 803
## HttpRequestOptions

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

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

S
shawn_he 已提交
804 805 806
| Name        | Type                                         | Mandatory| Description                                                        |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method         | [RequestMethod](#requestmethod)               | No  | Request method.                                                  |
S
shawn_he 已提交
807
| 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> |
S
shawn_he 已提交
808
| 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.|
S
shawn_he 已提交
809 810
| 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 已提交
811 812 813 814 815
| 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.             |
| usingProtocol<sup>9+</sup>   | [HttpProtocol](#httpprotocol9)  | No  | Protocol. The default value is automatically specified by the system.                            |
| usingProxy<sup>10+</sup>     | boolean \| Object               | No  | Whether to use HTTP proxy. The default value is **false**, which means not to use HTTP proxy.<br>- If **usingProxy** is of the **Boolean** type and the value is **true**, network proxy is used by default.<br>- If **usingProxy** is of the **object** type, the specified network proxy is used.                               |
S
shawn_he 已提交
816 817 818 819 820 821 822 823

## RequestMethod

Defines an HTTP request method.

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

| Name   | Value     | Description               |
S
shawn_he 已提交
824
| :------ | ------- | :------------------ |
S
shawn_he 已提交
825 826 827 828 829 830 831 832
| 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 已提交
833 834 835 836 837 838 839 840 841

## ResponseCode

Enumerates the response codes for an HTTP request.

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

| Name             | Value  | Description                                                        |
| ----------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
842
| 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 已提交
843
| CREATED           | 201  | "Created." The request has been successfully sent and a new resource is created.                          |
S
shawn_he 已提交
844
| ACCEPTED          | 202  | "Accepted." The request has been accepted, but the processing has not been completed.                        |
S
shawn_he 已提交
845 846 847
| 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 已提交
848
| PARTIAL           | 206  | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource.                     |
S
shawn_he 已提交
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
| 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 已提交
872
| NOT_IMPLEMENTED   | 501  | "Not Implemented." The server does not support the function required to fulfill the request.                      |
S
shawn_he 已提交
873 874 875 876 877 878 879 880 881 882 883 884 885
| 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 已提交
886
| 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 已提交
887
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9)             | Yes  | Type of the return value.                          |
S
shawn_he 已提交
888
| 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**.|
S
shawn_he 已提交
889
| 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'];|
S
shawn_he 已提交
890
| cookies<sup>8+</sup> | string                                       | Yes  | Cookies returned by the server.                                      |
S
shawn_he 已提交
891

S
shawn_he 已提交
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
## 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                                                        |
S
shawn_he 已提交
909
| :---------- | :----------------------------------------------------------- |
S
shawn_he 已提交
910 911 912 913 914 915 916 917 918 919 920
| [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>

S
shawn_he 已提交
921
Defines 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.
S
shawn_he 已提交
922 923 924

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

S
shawn_he 已提交
925
flush(callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
926 927 928 929 930 931 932 933 934

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      |
| -------- | --------------------------------------- | ---- | ---------- |
S
shawn_he 已提交
935
| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
S
shawn_he 已提交
936 937 938 939 940 941

**Example**

```js
httpResponseCache.flush(err => {
  if (err) {
S
shawn_he 已提交
942
    console.info('flush fail');
S
shawn_he 已提交
943 944
    return;
  }
S
shawn_he 已提交
945
  console.info('flush success');
S
shawn_he 已提交
946 947 948 949 950
});
```

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

S
shawn_he 已提交
951
flush(): Promise\<void\>
S
shawn_he 已提交
952 953 954 955 956 957 958 959 960

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                                 |
| --------------------------------- | ------------------------------------- |
S
shawn_he 已提交
961
| Promise\<void\> | Promise used to return the result.|
S
shawn_he 已提交
962 963 964 965 966

**Example**

```js
httpResponseCache.flush().then(() => {
S
shawn_he 已提交
967
  console.info('flush success');
S
shawn_he 已提交
968
}).catch(err => {
S
shawn_he 已提交
969
  console.info('flush fail');
S
shawn_he 已提交
970 971 972 973 974
});
```

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

S
shawn_he 已提交
975
delete(callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
976 977 978 979 980 981 982 983 984

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      |
| -------- | --------------------------------------- | ---- | ---------- |
S
shawn_he 已提交
985
| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
S
shawn_he 已提交
986 987 988 989 990 991

**Example**

```js
httpResponseCache.delete(err => {
  if (err) {
S
shawn_he 已提交
992
    console.info('delete fail');
S
shawn_he 已提交
993 994
    return;
  }
S
shawn_he 已提交
995
  console.info('delete success');
S
shawn_he 已提交
996 997 998 999
});
```
### delete<sup>9+</sup>

S
shawn_he 已提交
1000
delete(): Promise\<void\>
S
shawn_he 已提交
1001 1002 1003 1004 1005 1006 1007 1008 1009

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                                 |
| --------------------------------- | ------------------------------------- |
S
shawn_he 已提交
1010
| Promise\<void\> |  Promise used to return the result.|
S
shawn_he 已提交
1011 1012 1013 1014 1015

**Example**

```js
httpResponseCache.delete().then(() => {
S
shawn_he 已提交
1016
  console.info('delete success');
S
shawn_he 已提交
1017
}).catch(err => {
S
shawn_he 已提交
1018
  console.info('delete fail');
S
shawn_he 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
});
```

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

Enumerates HTTP data types.

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

| Name| Value| Description    |
S
shawn_he 已提交
1029
| ------------------  | -- | ----------- |
S
shawn_he 已提交
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
| 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    |
S
shawn_he 已提交
1041
| :-------- | :----------- |
S
shawn_he 已提交
1042 1043
| HTTP1_1   |  HTTP1.1 |
| HTTP2     |  HTTP2   |