js-apis-http.md 52.9 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
> **NOTE**
S
shawn_he 已提交
6 7 8
>
>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
## Examples
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
httpRequest.on('headersReceive', (header) => {
S
shawn_he 已提交
27
  console.info('header: ' + JSON.stringify(header));
S
shawn_he 已提交
28 29
});
httpRequest.request(
S
shawn_he 已提交
30 31 32 33 34 35 36 37
  // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
  "EXAMPLE_URL",
  {
    method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
    // You can add header fields based on service requirements.
    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
    expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
S
shawn_he 已提交
43 44 45 46 47
    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.
    readTimeout: 60000, // Optional. The default value is 60000, in ms.
    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
    caPath: "", // Optional. The preset CA certificate is used by default. This field is supported since API version 10.
S
shawn_he 已提交
50 51 52 53 54 55 56 57
  }, (err, data) => {
    if (!err) {
      // data.result carries the HTTP response. Parse the response based on service requirements.
      console.info('Result:' + JSON.stringify(data.result));
      console.info('code:' + JSON.stringify(data.responseCode));
      // data.header carries the HTTP response header. Parse the content based on service requirements.
      console.info('header:' + JSON.stringify(data.header));
      console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
S
shawn_he 已提交
58 59
      // Call the destroy() method to release resources after HttpRequest is complete.
      httpRequest.destroy();
S
shawn_he 已提交
60 61 62 63 64 65
    } else {
      console.info('error:' + JSON.stringify(err));
      // Unsubscribe from HTTP Response Header events.
      httpRequest.off('headersReceive');
      // Call the destroy() method to release resources after HttpRequest is complete.
      httpRequest.destroy();
S
shawn_he 已提交
66
    }
S
shawn_he 已提交
67
  }
S
shawn_he 已提交
68 69 70
);
```

S
shawn_he 已提交
71 72 73
> **NOTE**
> If the data in **console.info()** contains a newline character, the data will be truncated.

S
shawn_he 已提交
74
## http.createHttp<sup>6+</sup>
S
shawn_he 已提交
75

S
shawn_he 已提交
76
createHttp(): HttpRequest
S
shawn_he 已提交
77

S
shawn_he 已提交
78
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 已提交
79 80 81

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

S
shawn_he 已提交
82
**Return value**
S
shawn_he 已提交
83 84

| Type       | Description                                                        |
S
shawn_he 已提交
85
| :---------- | :----------------------------------------------------------- |
S
shawn_he 已提交
86
| HttpRequest | An **HttpRequest** object, which contains the **request**, **request2**, **destroy**, **on**, or **off** method.|
S
shawn_he 已提交
87 88 89

**Example**

S
shawn_he 已提交
90
```js
S
shawn_he 已提交
91
import http from '@ohos.net.http';
S
shawn_he 已提交
92

S
shawn_he 已提交
93 94 95 96 97
let httpRequest = http.createHttp();
```

## HttpRequest

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

S
shawn_he 已提交
100
### request<sup>6+</sup>
S
shawn_he 已提交
101

S
shawn_he 已提交
102
request(url: string, callback: AsyncCallback\<HttpResponse\>):void
S
shawn_he 已提交
103 104 105

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

S
shawn_he 已提交
106
> **NOTE**
S
shawn_he 已提交
107
> This API supports only receiving of data not greater than 5 MB.
S
shawn_he 已提交
108

S
shawn_he 已提交
109
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
110 111 112 113 114

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

**Parameters**

S
shawn_he 已提交
115 116 117
| Name  | Type                                          | Mandatory| Description                   |
| -------- | ---------------------------------------------- | ---- | ----------------------- |
| url      | string                                         | Yes  | URL for initiating an HTTP request.|
S
shawn_he 已提交
118 119
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes  | Callback used to return the result.             |

S
shawn_he 已提交
120 121
**Error codes**

S
shawn_he 已提交
122
| ID  | Error Message                                                 |
S
shawn_he 已提交
123 124 125
|---------|-------------------------------------------------------|
| 401     | Parameter error.                                      |
| 201     | Permission denied.                                    |
S
shawn_he 已提交
126
| 2300001 | Unsupported protocol.                                 |
S
shawn_he 已提交
127
| 2300003 | URL using bad/illegal format or missing URL.          |
S
shawn_he 已提交
128 129
| 2300005 | Couldn't resolve proxy name.                          |
| 2300006 | Couldn't resolve host name.                           |
S
shawn_he 已提交
130
| 2300007 | Couldn't connect to server.                           |
S
shawn_he 已提交
131 132 133 134 135 136 137 138
| 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.                                        |
S
shawn_he 已提交
139
| 2300028 | Timeout was reached.                                  |
S
shawn_he 已提交
140
| 2300047 | Number of redirects hit maximum amount.               |
S
shawn_he 已提交
141
| 2300052 | Server returned nothing (no headers, no data).        |
S
shawn_he 已提交
142 143 144 145 146 147 148 149 150 151 152 153
| 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.         |
S
shawn_he 已提交
154 155
| 2300999 | Unknown Other Error.                                  |

S
shawn_he 已提交
156
> **NOTE**
S
shawn_he 已提交
157 158 159
> 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 已提交
160 161
**Example**

S
shawn_he 已提交
162
```js
S
shawn_he 已提交
163
httpRequest.request("EXAMPLE_URL", (err, data) => {
S
shawn_he 已提交
164 165 166 167 168 169 170 171
  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 已提交
172 173 174
});
```

S
shawn_he 已提交
175
### request<sup>6+</sup>
S
shawn_he 已提交
176

S
shawn_he 已提交
177
request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpResponse\>):void
S
shawn_he 已提交
178 179 180

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

S
shawn_he 已提交
181
> **NOTE**
S
shawn_he 已提交
182
> This API supports only receiving of data not greater than 5 MB.
S
shawn_he 已提交
183

S
shawn_he 已提交
184
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
185 186 187 188 189 190 191 192 193 194 195

**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 已提交
196 197
**Error codes**

S
shawn_he 已提交
198
| ID  | Error Message                                                 |
S
shawn_he 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
|---------|-------------------------------------------------------|
| 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.                                  |

S
shawn_he 已提交
232
> **NOTE**
S
shawn_he 已提交
233 234 235
> 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 已提交
236 237
**Example**

S
shawn_he 已提交
238
```js
S
shawn_he 已提交
239
httpRequest.request("EXAMPLE_URL",
S
shawn_he 已提交
240
  {
S
shawn_he 已提交
241
    method: http.RequestMethod.GET,
S
shawn_he 已提交
242
    header: {
S
shawn_he 已提交
243
      'Content-Type': 'application/json'
S
shawn_he 已提交
244 245 246
    },
    readTimeout: 60000,
    connectTimeout: 60000
S
shawn_he 已提交
247
  }, (err, data) => {
S
shawn_he 已提交
248
    if (!err) {
S
shawn_he 已提交
249 250 251 252 253 254
      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 已提交
255
    } else {
S
shawn_he 已提交
256
      console.info('error:' + JSON.stringify(err));
S
shawn_he 已提交
257
    }
S
shawn_he 已提交
258
  });
S
shawn_he 已提交
259 260
```

S
shawn_he 已提交
261
### request<sup>6+</sup>
S
shawn_he 已提交
262

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

S
shawn_he 已提交
265
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. 
S
shawn_he 已提交
266

S
shawn_he 已提交
267
> **NOTE**
S
shawn_he 已提交
268
> This API supports only receiving of data not greater than 5 MB.
S
shawn_he 已提交
269

S
shawn_he 已提交
270
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
271 272 273 274 275

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

**Parameters**

S
shawn_he 已提交
276 277 278
| Name | Type              | Mandatory| Description                                           |
| ------- | ------------------ | ---- | ----------------------------------------------- |
| url     | string             | Yes  | URL for initiating an HTTP request.                        |
S
shawn_he 已提交
279
| options | HttpRequestOptions | No  | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
S
shawn_he 已提交
280

S
shawn_he 已提交
281
**Return value**
S
shawn_he 已提交
282

S
shawn_he 已提交
283
| Type                                  | Description                             |
S
shawn_he 已提交
284
| :------------------------------------- | :-------------------------------- |
S
shawn_he 已提交
285 286
| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.|

S
shawn_he 已提交
287 288
**Error codes**

S
shawn_he 已提交
289
| ID  | Error Message                                                 |
S
shawn_he 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
|---------|-------------------------------------------------------|
| 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.                                  |

S
shawn_he 已提交
323
> **NOTE**
S
shawn_he 已提交
324 325
> 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 已提交
326 327 328

**Example**

S
shawn_he 已提交
329
```js
S
shawn_he 已提交
330
let promise = httpRequest.request("EXAMPLE_URL", {
S
shawn_he 已提交
331 332 333 334 335 336
  method: http.RequestMethod.GET,
  connectTimeout: 60000,
  readTimeout: 60000,
  header: {
    'Content-Type': 'application/json'
  }
S
shawn_he 已提交
337
});
S
shawn_he 已提交
338
promise.then((data) => {
S
shawn_he 已提交
339 340 341 342 343 344
  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 已提交
345
}).catch((err) => {
S
shawn_he 已提交
346
  console.info('error:' + JSON.stringify(err));
S
shawn_he 已提交
347 348 349 350 351
});
```

### destroy

S
shawn_he 已提交
352
destroy(): void
S
shawn_he 已提交
353 354 355 356 357 358 359

Destroys an HTTP request.

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

**Example**

S
shawn_he 已提交
360
```js
S
shawn_he 已提交
361 362 363
httpRequest.destroy();
```

S
shawn_he 已提交
364 365
### request2<sup>10+</sup>

S
shawn_he 已提交
366
request2(url: string, callback: AsyncCallback\<number\>): void
S
shawn_he 已提交
367

S
shawn_he 已提交
368
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
S
shawn_he 已提交
369 370 371 372 373 374 375 376 377 378

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

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

**Parameters**

| Name  | Type                                          | Mandatory| Description                                           |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url      | string                                         | Yes  | URL for initiating an HTTP request.                        |
S
shawn_he 已提交
379
| callback | AsyncCallback\<[number](#responsecode)\>       | Yes  | Callback used to return the result.                                     |
S
shawn_he 已提交
380 381 382

**Error codes**

S
shawn_he 已提交
383
| ID  | Error Message                                                 |
S
shawn_he 已提交
384 385 386
|---------|-------------------------------------------------------|
| 401     | Parameter error.                                      |
| 201     | Permission denied.                                    |
S
shawn_he 已提交
387
| 2300001 | Unsupported protocol.                                 |
S
shawn_he 已提交
388
| 2300003 | URL using bad/illegal format or missing URL.          |
S
shawn_he 已提交
389 390
| 2300005 | Couldn't resolve proxy name.                          |
| 2300006 | Couldn't resolve host name.                           |
S
shawn_he 已提交
391
| 2300007 | Couldn't connect to server.                           |
S
shawn_he 已提交
392 393 394 395 396 397 398 399
| 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.                                        |
S
shawn_he 已提交
400
| 2300028 | Timeout was reached.                                  |
S
shawn_he 已提交
401
| 2300047 | Number of redirects hit maximum amount.               |
S
shawn_he 已提交
402
| 2300052 | Server returned nothing (no headers, no data).        |
S
shawn_he 已提交
403 404 405 406 407 408 409 410 411 412 413 414
| 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.         |
S
shawn_he 已提交
415 416
| 2300999 | Unknown Other Error.                                  |

S
shawn_he 已提交
417
> **NOTE**
S
shawn_he 已提交
418 419 420 421 422 423
> 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
S
shawn_he 已提交
424
httpRequest.request2("EXAMPLE_URL", (err, data) => {
S
shawn_he 已提交
425 426 427 428 429
  if (!err) {
    console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
  } else {
    console.info("request2 ERROR : err = " + JSON.stringify(err));
  }
S
shawn_he 已提交
430 431 432 433 434
})
```

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

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

S
shawn_he 已提交
437
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 已提交
438 439 440 441 442 443 444 445 446 447 448

**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).|
S
shawn_he 已提交
449
| callback | AsyncCallback\<[number](#responsecode)\>       | Yes  | Callback used to return the result.                                     |
S
shawn_he 已提交
450 451 452

**Error codes**

S
shawn_he 已提交
453
| ID  | Error Message                                                 |
S
shawn_he 已提交
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
|---------|-------------------------------------------------------|
| 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.                                  |

S
shawn_he 已提交
487
> **NOTE**
S
shawn_he 已提交
488 489 490 491 492 493 494
> 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",
S
shawn_he 已提交
495
  {
S
shawn_he 已提交
496 497
    method: http.RequestMethod.GET,
    header: {
S
shawn_he 已提交
498
      'Content-Type': 'application/json'
S
shawn_he 已提交
499 500 501
    },
    readTimeout: 60000,
    connectTimeout: 60000
S
shawn_he 已提交
502
  }, (err, data) => {
S
shawn_he 已提交
503
    if (!err) {
S
shawn_he 已提交
504
      console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
S
shawn_he 已提交
505
    } else {
S
shawn_he 已提交
506
      console.info("request2 ERROR : err = " + JSON.stringify(err));
S
shawn_he 已提交
507
    }
S
shawn_he 已提交
508
  })
S
shawn_he 已提交
509
```
S
shawn_he 已提交
510

S
shawn_he 已提交
511 512
### request2<sup>10+</sup>

S
shawn_he 已提交
513
request2(url: string, options? : HttpRequestOptions): Promise\<number\>
S
shawn_he 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

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                             |
S
shawn_he 已提交
531
| :------------------------------------- | :-------------------------------- |
S
shawn_he 已提交
532
| Promise\<[number](#responsecode)\> | Promise used to return the result.|
S
shawn_he 已提交
533 534 535

**Error codes**

S
shawn_he 已提交
536
| ID  | Error Message                                                 |
S
shawn_he 已提交
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
|---------|-------------------------------------------------------|
| 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.                                  |

S
shawn_he 已提交
570
> **NOTE**
S
shawn_he 已提交
571
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
S
shawn_he 已提交
572
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see:
S
shawn_he 已提交
573 574 575 576

**Example**

```js
S
shawn_he 已提交
577 578 579 580 581 582 583
let promise = httpRequest.request2("EXAMPLE_URL", {
  method: http.RequestMethod.GET,
  connectTimeout: 60000,
  readTimeout: 60000,
  header: {
    'Content-Type': 'application/json'
  }
S
shawn_he 已提交
584
});
S
shawn_he 已提交
585
promise.then((data) => {
S
shawn_he 已提交
586
  console.info("request2 OK!" + JSON.stringify(data));
S
shawn_he 已提交
587
}).catch((err) => {
S
shawn_he 已提交
588
  console.info("request2 ERROR : err = " + JSON.stringify(err));
S
shawn_he 已提交
589 590 591
});
```

S
shawn_he 已提交
592
### on('headerReceive')<sup>(deprecated)</sup>
S
shawn_he 已提交
593

S
shawn_he 已提交
594
on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void
S
shawn_he 已提交
595 596 597

Registers an observer for HTTP Response Header events.

S
shawn_he 已提交
598
> **NOTE**
S
shawn_he 已提交
599
> This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8) instead.
S
shawn_he 已提交
600 601 602 603 604 605 606 607 608 609 610 611

**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 已提交
612
```js
S
shawn_he 已提交
613
httpRequest.on('headerReceive', (data) => {
S
shawn_he 已提交
614
  console.info('error:' + JSON.stringify(data));
S
shawn_he 已提交
615 616 617
});
```

S
shawn_he 已提交
618
### off('headerReceive')<sup>(deprecated)</sup>
S
shawn_he 已提交
619

S
shawn_he 已提交
620
off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void
S
shawn_he 已提交
621 622 623

Unregisters the observer for HTTP Response Header events.

S
shawn_he 已提交
624
> **NOTE**
S
shawn_he 已提交
625
>
S
shawn_he 已提交
626
>1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8) instead.
S
shawn_he 已提交
627 628 629 630 631 632 633 634 635 636 637 638 639 640
>
>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 已提交
641
```js
S
shawn_he 已提交
642 643 644
httpRequest.off('headerReceive');
```

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

S
shawn_he 已提交
647
on(type: 'headersReceive', callback: Callback\<Object\>): void
S
shawn_he 已提交
648 649 650 651 652 653 654 655 656 657 658 659 660 661

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 已提交
662
```js
S
shawn_he 已提交
663
httpRequest.on('headersReceive', (header) => {
S
shawn_he 已提交
664
  console.info('header: ' + JSON.stringify(header));
S
shawn_he 已提交
665 666 667
});
```

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

S
shawn_he 已提交
670
off(type: 'headersReceive', callback?: Callback\<Object\>): void
S
shawn_he 已提交
671 672 673

Unregisters the observer for HTTP Response Header events.

S
shawn_he 已提交
674 675
> **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.
S
shawn_he 已提交
676 677 678 679 680 681 682 683 684 685 686 687

**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 已提交
688
```js
S
shawn_he 已提交
689 690 691
httpRequest.off('headersReceive');
```

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

S
shawn_he 已提交
694
once(type: 'headersReceive', callback: Callback\<Object\>): void
S
shawn_he 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707 708

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 已提交
709
```js
S
shawn_he 已提交
710
httpRequest.once('headersReceive', (header) => {
S
shawn_he 已提交
711
  console.info('header: ' + JSON.stringify(header));
S
shawn_he 已提交
712 713
});
```
S
shawn_he 已提交
714

S
shawn_he 已提交
715
### on('dataReceive')<sup>10+</sup>
S
shawn_he 已提交
716

S
shawn_he 已提交
717
on(type: 'dataReceive', callback: Callback\<ArrayBuffer\>): void
S
shawn_he 已提交
718 719

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

S
shawn_he 已提交
721 722 723 724 725 726 727 728 729 730 731 732 733
**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) => {
S
shawn_he 已提交
734
  console.info('dataReceive length: ' + JSON.stringify(data.byteLength));
S
shawn_he 已提交
735 736 737
});
```

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

S
shawn_he 已提交
740
off(type: 'dataReceive', callback?: Callback\<ArrayBuffer\>): void
S
shawn_he 已提交
741 742 743

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

S
shawn_he 已提交
744 745
> **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.
S
shawn_he 已提交
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761

**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 已提交
762
### on('dataEnd')<sup>10+</sup>
S
shawn_he 已提交
763

S
shawn_he 已提交
764
on(type: 'dataEnd', callback: Callback\<void\>): void
S
shawn_he 已提交
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779

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
S
shawn_he 已提交
780 781
httpRequest.on('dataEnd', () => {
  console.info('Receive dataEnd !');
S
shawn_he 已提交
782 783 784
});
```

S
shawn_he 已提交
785
### off('dataEnd')<sup>10+</sup>
S
shawn_he 已提交
786 787 788 789 790

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

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

S
shawn_he 已提交
791 792
> **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.
S
shawn_he 已提交
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808

**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 已提交
809
### on('dataProgress')<sup>10+</sup>
S
shawn_he 已提交
810

S
shawn_he 已提交
811
on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void
S
shawn_he 已提交
812 813 814 815 816 817 818 819 820 821

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 已提交
822
| 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 已提交
823 824 825 826 827

**Example**

```js
httpRequest.on('dataProgress', (data) => {
S
shawn_he 已提交
828
  console.info('dataProgress:' + JSON.stringify(data));
S
shawn_he 已提交
829 830 831
});
```

S
shawn_he 已提交
832
### off('dataProgress')<sup>10+</sup>
S
shawn_he 已提交
833 834 835 836 837

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

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

S
shawn_he 已提交
838 839
> **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.
S
shawn_he 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854

**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 已提交
855

S
shawn_he 已提交
856
## HttpRequestOptions<sup>6+</sup>
S
shawn_he 已提交
857 858 859 860 861

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

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

S
shawn_he 已提交
862 863
| Name        | Type                                         | Mandatory| Description                                                        |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
864
| method         | [RequestMethod](#requestmethod)               | No  | Request method. The default value is **GET**.                                                  |
S
shawn_he 已提交
865
| 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.|
S
shawn_he 已提交
866
| 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.|
S
shawn_he 已提交
867
| usingCache<sup>9+</sup>      | boolean                         | No  | Whether to use the cache. The default value is **true**.  |
S
shawn_he 已提交
868
| priority<sup>9+</sup>        | number                          | No  | Priority. The value range is [1,1000]. The default value is **1**.                          |
S
shawn_he 已提交
869
| header                       | Object                          | No  | HTTP request header. The default value is **{'Content-Type': 'application/json'}**.  |
S
shawn_he 已提交
870
| readTimeout                  | number                          | No  | Read timeout duration. The default value is **60000**, in ms.<br>The value **0** indicates no timeout.|
S
shawn_he 已提交
871 872
| 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.                            |
S
shawn_he 已提交
873 874
| 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.
| caPath<sup>10+</sup>     | string               | No  | Path of the CA certificate. If this parameter is set, the system uses the CA certificate in the specified path. Otherwise, the system uses the preset CA certificate.                            |
S
shawn_he 已提交
875

S
shawn_he 已提交
876
## RequestMethod<sup>6+</sup>
S
shawn_he 已提交
877 878 879 880 881 882

Defines an HTTP request method.

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

| Name   | Value     | Description               |
S
shawn_he 已提交
883
| :------ | ------- | :------------------ |
S
shawn_he 已提交
884 885 886 887 888 889 890 891
| 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 已提交
892

S
shawn_he 已提交
893
## ResponseCode<sup>6+</sup>
S
shawn_he 已提交
894 895 896 897 898 899 900

Enumerates the response codes for an HTTP request.

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

| Name             | Value  | Description                                                        |
| ----------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
901
| OK                | 200  | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests.                           |
S
shawn_he 已提交
902
| CREATED           | 201  | "Created." The request has been successfully sent and a new resource is created.                          |
S
shawn_he 已提交
903
| ACCEPTED          | 202  | "Accepted." The request has been accepted, but the processing has not been completed.                        |
S
shawn_he 已提交
904 905 906
| 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 已提交
907
| PARTIAL           | 206  | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource.                     |
S
shawn_he 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
| 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 已提交
931
| NOT_IMPLEMENTED   | 501  | "Not Implemented." The server does not support the function required to fulfill the request.                      |
S
shawn_he 已提交
932 933 934 935 936
| 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.                                 |

S
shawn_he 已提交
937
## HttpResponse<sup>6+</sup>
S
shawn_he 已提交
938 939 940 941 942 943 944

Defines the response to an HTTP request.

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

| Name              | Type                                        | Mandatory| Description                                                        |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
945
| 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|
S
shawn_he 已提交
946
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9)             | Yes  | Type of the return value.                          |
S
shawn_he 已提交
947
| 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 已提交
948
| 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 已提交
949
| cookies<sup>8+</sup> | string                                       | Yes  | Cookies returned by the server.                                      |
S
shawn_he 已提交
950

S
shawn_he 已提交
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
## 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 已提交
968
| :---------- | :----------------------------------------------------------- |
S
shawn_he 已提交
969 970 971 972 973 974
| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.|

**Example**

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

S
shawn_he 已提交
976 977 978 979 980
let httpResponseCache = http.createHttpResponseCache();
```

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

S
shawn_he 已提交
981
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 已提交
982 983 984

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

S
shawn_he 已提交
985
flush(callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
986 987 988 989 990 991 992 993 994

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 已提交
995
| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
S
shawn_he 已提交
996 997 998 999 1000 1001

**Example**

```js
httpResponseCache.flush(err => {
  if (err) {
S
shawn_he 已提交
1002
    console.info('flush fail');
S
shawn_he 已提交
1003 1004
    return;
  }
S
shawn_he 已提交
1005
  console.info('flush success');
S
shawn_he 已提交
1006 1007 1008 1009 1010
});
```

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

S
shawn_he 已提交
1011
flush(): Promise\<void\>
S
shawn_he 已提交
1012 1013 1014 1015 1016 1017 1018 1019 1020

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 已提交
1021
| Promise\<void\> | Promise used to return the result.|
S
shawn_he 已提交
1022 1023 1024 1025 1026

**Example**

```js
httpResponseCache.flush().then(() => {
S
shawn_he 已提交
1027
  console.info('flush success');
S
shawn_he 已提交
1028
}).catch(err => {
S
shawn_he 已提交
1029
  console.info('flush fail');
S
shawn_he 已提交
1030 1031 1032 1033 1034
});
```

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

S
shawn_he 已提交
1035
delete(callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
1036 1037 1038 1039 1040 1041 1042 1043 1044

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 已提交
1045
| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
S
shawn_he 已提交
1046 1047 1048 1049 1050 1051

**Example**

```js
httpResponseCache.delete(err => {
  if (err) {
S
shawn_he 已提交
1052
    console.info('delete fail');
S
shawn_he 已提交
1053 1054
    return;
  }
S
shawn_he 已提交
1055
  console.info('delete success');
S
shawn_he 已提交
1056 1057
});
```
S
shawn_he 已提交
1058

S
shawn_he 已提交
1059 1060
### delete<sup>9+</sup>

S
shawn_he 已提交
1061
delete(): Promise\<void\>
S
shawn_he 已提交
1062 1063 1064 1065 1066 1067 1068 1069 1070

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 已提交
1071
| Promise\<void\> | Promise used to return the result.|
S
shawn_he 已提交
1072 1073 1074 1075 1076

**Example**

```js
httpResponseCache.delete().then(() => {
S
shawn_he 已提交
1077
  console.info('delete success');
S
shawn_he 已提交
1078
}).catch(err => {
S
shawn_he 已提交
1079
  console.info('delete fail');
S
shawn_he 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
});
```

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

Enumerates HTTP data types.

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

| Name| Value| Description    |
S
shawn_he 已提交
1090
| ------------------  | -- | ----------- |
S
shawn_he 已提交
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
| 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 已提交
1102
| :-------- | :----------- |
S
shawn_he 已提交
1103 1104
| HTTP1_1   |  HTTP1.1 |
| HTTP2     |  HTTP2   |