http-request.md 9.7 KB
Newer Older
S
shawn_he 已提交
1 2
# HTTP Data Request

S
shawn_he 已提交
3
## When to Use
S
shawn_he 已提交
4 5 6 7 8 9 10 11 12

An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.

## Available APIs

The HTTP request function is mainly implemented by the HTTP module.

To use related APIs, you must declare the **ohos.permission.INTERNET** permission.

S
shawn_he 已提交
13 14
For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md).

S
shawn_he 已提交
15
The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
S
shawn_he 已提交
16

S
shawn_he 已提交
17 18 19 20 21 22
| API                                   | Description                           |
| ----------------------------------------- | ----------------------------------- |
| createHttp()                              | Creates an HTTP request.                 |
| request()                                 | Initiates an HTTP request to a given URL.    |
| request2()<sup>10+</sup>                  | Initiates an HTTP network request based on the URL and returns a streaming response.|
| destroy()                                 | Destroys an HTTP request.                     |
S
shawn_he 已提交
23
| on(type: 'headersReceive')                | Registers an observer for HTTP Response Header events.    |
S
shawn_he 已提交
24 25 26 27 28 29 30 31
| off(type: 'headersReceive')               | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup>     | Registers a one-time observer for HTTP Response Header events.|
| on\('dataReceive'\)<sup>10+</sup>         | Registers an observer for events indicating receiving of HTTP streaming responses.     |
| off\('dataReceive'\)<sup>10+</sup>        | Unregisters the observer for events indicating receiving of HTTP streaming responses. |
| on\('dataEnd'\)<sup>10+</sup>             | Registers an observer for events indicating completion of receiving HTTP streaming responses. |
| off\('dataEnd'\)<sup>10+</sup>            | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.|
| on\('dataProgress'\)<sup>10+</sup>        | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
| off\('dataProgress'\)<sup>10+</sup>       | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
S
shawn_he 已提交
32

S
shawn_he 已提交
33
## How to Develop request APIs
S
shawn_he 已提交
34

S
shawn_he 已提交
35 36 37 38 39 40 41
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned result based on service requirements.
6. Call **off()** to unsubscribe from HTTP response header events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
S
shawn_he 已提交
42 43

```js
S
shawn_he 已提交
44
// Import the http namespace.
S
shawn_he 已提交
45 46
import http from '@ohos.net.http';

S
shawn_he 已提交
47
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
S
shawn_he 已提交
48
let httpRequest = http.createHttp();
S
shawn_he 已提交
49 50
// 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.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
S
shawn_he 已提交
51 52 53 54
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
S
shawn_he 已提交
55
    // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
S
shawn_he 已提交
56 57 58
    "EXAMPLE_URL",
    {
        method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
S
shawn_he 已提交
59
        // You can add header fields based on service requirements.
S
shawn_he 已提交
60 61 62 63 64 65 66
        header: {
            'Content-Type': 'application/json'
        },
        // This field is used to transfer data when the POST request is used.
        extraData: {
            "data": "data to send",
        },
S
shawn_he 已提交
67 68 69 70
        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 已提交
71
        readTimeout: 60000, // Optional. The default value is 60000, in ms.
S
shawn_he 已提交
72 73
        usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
        usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
S
shawn_he 已提交
74 75
    }, (err, data) => {
        if (!err) {
S
shawn_he 已提交
76 77 78 79
            // 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.
S
shawn_he 已提交
80
            console.info('header:' + JSON.stringify(data.header));
S
shawn_he 已提交
81
            console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
S
shawn_he 已提交
82 83
        } else {
            console.info('error:' + JSON.stringify(err));
S
shawn_he 已提交
84 85 86
            // Unsubscribe from HTTP Response Header events.
            httpRequest.off('headersReceive');
            // Call the destroy() method to release resources after HttpRequest is complete.
S
shawn_he 已提交
87 88 89 90 91
            httpRequest.destroy();
        }
    }
);
```
S
shawn_he 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

## How to Develop request2 APIs

1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Depending on your need, call **on()** of the **HttpRequest** object to subscribe to HTTP response header events as well as events indicating receiving of HTTP streaming responses, progress of receiving HTTP streaming responses, and completion of receiving HTTP streaming responses.
4. Call **request2()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned response code as needed.
6. Call **off()** of the **HttpRequest** object to unsubscribe from the related events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.

```js
// Import the http namespace.
import http from '@ohos.net.http'

// Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp();
// Subscribe to HTTP response header events.
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
});
// Subscribe to events indicating receiving of HTTP streaming responses.
let res = '';
httpRequest.on('dataReceive', (data) => {
    res += data;
    console.info('res: ' + res);
});
// Subscribe to events indicating completion of receiving HTTP streaming responses.
httpRequest.on('dataEnd', () => {
    console.info('No more data in response, data receive end');
});
// Subscribe to events indicating progress of receiving HTTP streaming responses.
httpRequest.on('dataProgress', (data) => {
    console.log("dataProgress receiveSize:" + data.receiveSize+ ", totalSize:" + data.totalSize);
});

httpRequest.request2(
    // 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'
        },
        // This field is used to transfer data when the POST request is used.
        extraData: {
            "data": "data to send",
        },
        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.
        readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission.
        usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
    }, (err, data) => {
            console.info('error:' + JSON.stringify(err));
            console.info('ResponseCode :' + JSON.stringify(data));
            // Unsubscribe from HTTP Response Header events.
            httpRequest.off('headersReceive');
            // Unregister the observer for events indicating receiving of HTTP streaming responses.
            httpRequest.off('dataReceive');
            // Unregister the observer for events indicating progress of receiving HTTP streaming responses.
            httpRequest.off('dataProgress');
            // Unregister the observer for events indicating completion of receiving HTTP streaming responses.
            httpRequest.off('dataEnd');
            // Call the destroy() method to release resources after HttpRequest is complete.
            httpRequest.destroy();
        }
);

```

## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [HTTP Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)