js-apis-http.md 21.6 KB
Newer Older
S
shawn_he 已提交
1 2
# Data Request

S
shawn_he 已提交
3
>![](public_sys-resources/icon-note.gif) **NOTE**
S
shawn_he 已提交
4 5 6 7 8 9 10 11 12 13
>
>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.
>

## Modules to Import

```
import http from '@ohos.net.http';
```

S
shawn_he 已提交
14
## Example
S
shawn_he 已提交
15 16 17 18

```
import http from '@ohos.net.http';

S
shawn_he 已提交
19
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
S
shawn_he 已提交
20
let httpRequest = http.createHttp();
S
shawn_he 已提交
21
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements.
S
shawn_he 已提交
22
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
S
shawn_he 已提交
23 24
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
S
shawn_he 已提交
25 26
});
httpRequest.request(
S
shawn_he 已提交
27
    // Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData.
S
shawn_he 已提交
28 29
    "EXAMPLE_URL",
    {
S
shawn_he 已提交
30 31
        method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
        // You can add the header field based on service requirements.
S
shawn_he 已提交
32 33 34
        header: {
            'Content-Type': 'application/json'
        },
S
shawn_he 已提交
35
        // This field is used to transfer data when the POST request is used.
S
shawn_he 已提交
36 37 38
        extraData: {
            "data": "data to send",
        },
S
shawn_he 已提交
39 40
        connectTimeout: 60000, // Optional. The default value is 60000, in ms.
        readTimeout: 60000, // Optional. The default value is 60000, in ms.
S
shawn_he 已提交
41
    }, (err, data) => {
S
shawn_he 已提交
42
        if (!err) {
S
shawn_he 已提交
43
            // data.result contains the HTTP response. Parse the response based on service requirements.
S
shawn_he 已提交
44 45
            console.info('Result:' + data.result);
            console.info('code:' + data.responseCode);
S
shawn_he 已提交
46 47
            // data.header contains the HTTP response header. Parse the content based on service requirements.
            console.info('header:' + JSON.stringify(data.header));
S
shawn_he 已提交
48 49
            console.info('cookies:' + data.cookies); // 8+
        } else {
S
shawn_he 已提交
50 51
            console.info('error:' + JSON.stringify(err));
            // Call the destroy() method to release resources after the call is complete.
S
shawn_he 已提交
52 53 54 55 56 57 58 59 60 61
            httpRequest.destroy();
        }
    }
);
```

## http.createHttp

createHttp\(\): HttpRequest

S
shawn_he 已提交
62
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 已提交
63 64 65

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

S
shawn_he 已提交
66
**Return value**
S
shawn_he 已提交
67 68 69

| Type       | Description                                                        |
| :---------- | :----------------------------------------------------------- |
S
shawn_he 已提交
70
| HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.|
S
shawn_he 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

**Example**

```
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```


## HttpRequest

Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.

### request

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

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

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

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

**Parameters**

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

**Example**

```
httpRequest.request("EXAMPLE_URL", (err, data) => {
S
shawn_he 已提交
105 106 107 108 109 110 111 112
    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 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
});
```

### request

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

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

**Required permission**: 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\<[HttpResponse](#httpresponse)\> | Yes  | Callback used to return the result.                                     |

**Example**

```
httpRequest.request("EXAMPLE_URL",
{
S
shawn_he 已提交
139
    method: http.RequestMethod.GET,
S
shawn_he 已提交
140 141 142 143 144 145 146 147 148
    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 已提交
149
        console.info('header:' + JSON.stringify(data.header));
S
shawn_he 已提交
150 151 152 153
        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 已提交
154
        console.info('error:' + JSON.stringify(err));
S
shawn_he 已提交
155
    }
S
shawn_he 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
});
```


### request

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

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

**Required permission**: 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 已提交
177
**Return value**
S
shawn_he 已提交
178 179 180 181 182 183 184 185 186 187

| Type                 | Description                             |
| :-------------------- | :-------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.|


**Example**

```
let promise = httpRequest.request("EXAMPLE_URL", {
S
shawn_he 已提交
188
    method: http.RequestMethod.GET,
S
shawn_he 已提交
189 190 191 192 193
    connectTimeout: 60000,
    readTimeout: 60000,
    header: {
        'Content-Type': 'application/json'
    }
S
shawn_he 已提交
194
});
S
shawn_he 已提交
195 196 197 198 199 200 201
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 已提交
202
}).catch((err) => {
S
shawn_he 已提交
203
    console.info('error:' + JSON.stringify(err));
S
shawn_he 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
});
```

### destroy

destroy\(\): void

Destroys an HTTP request.

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

**Example**

```
httpRequest.destroy();
```

### on\('headerReceive'\)

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

Registers an observer for HTTP Response Header events.

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

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

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


### off\('headerReceive'\)

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

Unregisters the observer for HTTP Response Header events.

S
shawn_he 已提交
259
>![](public_sys-resources/icon-note.gif) **NOTE**
S
shawn_he 已提交
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 295 296 297
>
>1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead.
>
>2. You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.

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

**Parameters**

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

**Example**

```
httpRequest.off('headerReceive');
```

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

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

Registers an observer for HTTP Response Header events.

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

**Parameters**

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

**Example**

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


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

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

Unregisters the observer for HTTP Response Header events.

S
shawn_he 已提交
310
>![](public_sys-resources/icon-note.gif) **NOTE**
S
shawn_he 已提交
311
>
S
shawn_he 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
>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**

```
httpRequest.off('headersReceive');
```

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

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

Registers a one-time observer for HTTP Response Header events. Once triggered, the observer will be removed. This API uses an asynchronous callback to return the result.

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

**Parameters**

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

**Example**

```
S
shawn_he 已提交
347 348
httpRequest.once('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
S
shawn_he 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 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
});
```

## HttpRequestOptions

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

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

| Name         | Type                                | Mandatory| Description                                                      |
| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- |
| method         | [RequestMethod](#requestmethod) | No  | Request method.                                                |
| extraData      | string \| Object  \| ArrayBuffer<sup>8+</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>8+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> |
| 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.           |

## RequestMethod

Defines an HTTP request method.

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

| Name   | Value     | Description               |
| :------ | ------- | :------------------ |
| 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.|

## ResponseCode

Enumerates the response codes for an HTTP request.

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

| Name             | Value  | Description                                                        |
| ----------------- | ---- | ------------------------------------------------------------ |
| OK                | 200  | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests.                           |
| CREATED           | 201  | "Created." The request has been successfully sent and a new resource is created.                          |
| ACCEPTED          | 202  | "Accepted." The request has been accepted, but the processing has not been completed.                         |
| 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.                                                  |
| PARTIAL           | 206  | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource.                      |
| 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.                              |
| NOT_IMPLEMENTED   | 501  | "Not Implemented." The server does not support the function required to fulfill the request.                       |
| 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                                                        |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result               | string \| Object \| 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|
| 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**. The error code can be one of the following:<br>- 200: common error<br>- 202: parameter error<br>- 300: I/O error|
| header               | Object                                       | Yes  | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| cookies<sup>8+</sup> | Array\<string\>                              | Yes  | Cookies returned by the server.                                      |