提交 661ccb4a 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 80ff84eb
...@@ -53,7 +53,6 @@ httpRequest.on('headersReceive', (header) => { ...@@ -53,7 +53,6 @@ httpRequest.on('headersReceive', (header) => {
}); });
httpRequest.request( httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. // 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. method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements. // You can add header fields based on service requirements.
...@@ -122,7 +121,7 @@ httpRequest.on('dataEnd', () => { ...@@ -122,7 +121,7 @@ httpRequest.on('dataEnd', () => {
}); });
// Subscribe to events indicating progress of receiving HTTP streaming responses. // Subscribe to events indicating progress of receiving HTTP streaming responses.
httpRequest.on('dataProgress', (data) => { httpRequest.on('dataProgress', (data) => {
console.log("dataProgress receiveSize:" + data.receiveSize+ ", totalSize:" + data.totalSize); console.log("dataProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
}); });
httpRequest.request2( httpRequest.request2(
...@@ -161,8 +160,3 @@ httpRequest.request2( ...@@ -161,8 +160,3 @@ httpRequest.request2(
); );
``` ```
\ No newline at end of file
## 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)
# Network Connection Management # Network Connection Management
## Introduction ## Introduction
The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
> **NOTE** > **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md). > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md).
## Basic Concepts ## Basic Concepts
- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet. - Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet.
- Consumer: a user of data networks, for example, an application or a system service. - Consumer: a user of data networks, for example, an application or a system service.
- Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection. - Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection.
- Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes. - Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes.
## **Constraints** ## **Constraints**
- Programming language: C++ and JS - Programming language: C++ and JS
- System: Linux kernel - System: Linux kernel
- The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## When to Use ## When to Use
Typical application scenarios of network connection management are as follows: Typical application scenarios of network connection management are as follows:
- Subscribing to status changes of the specified network - Subscribing to status changes of the specified network
- Obtaining the list of all registered networks - Obtaining the list of all registered networks
- Querying network connection information based on the data network - Querying network connection information based on the data network
- Resolving the domain name of a network to obtain all IP addresses - Resolving the domain name of a network to obtain all IP addresses
The following describes the development procedure specific to each application scenario. The following describes the development procedure specific to each application scenario.
## Available APIs ## Available APIs
For the complete list of APIs and example code, see [Network Connection Management](../reference/apis/js-apis-net-connection.md). For the complete list of APIs and example code, see [Network Connection Management](../reference/apis/js-apis-net-connection.md).
| Type| API| Description| | Type| API| Description|
...@@ -75,39 +82,41 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -75,39 +82,41 @@ For the complete list of APIs and example code, see [Network Connection Manageme
```js ```js
// Import the connection namespace. // Import the connection namespace.
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
let netCap = { let netCap = {
// Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR. // Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR.
bearerTypes: [connection.NetBearType.BEARER_CELLULAR], bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
// Set the network capability to INTERNET. // Set the network capability to INTERNET.
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET], networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET],
}; };
let netSpec = { let netSpec = {
netCapabilities: netCap, netCapabilities: netCap,
}; };
// Set the timeout value to 10s. The default value is 0. // Set the timeout value to 10s. The default value is 0.
let timeout = 10 * 1000; let timeout = 10 * 1000;
// Create a NetConnection object. // Create a NetConnection object.
let conn = connection.createNetConnection(netSpec, timeout); let conn = connection.createNetConnection(netSpec, timeout);
// Listen to network status change events. If the network is available, an on_netAvailable event is returned. // Listen to network status change events. If the network is available, an on_netAvailable event is returned.
conn.on('netAvailable', (data=> { conn.on('netAvailable', (data => {
console.log("net is available, netId is " + data.netId); console.log("net is available, netId is " + data.netId);
})); }));
// Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned. // Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned.
conn.on('netUnavailable', (data=> { conn.on('netUnavailable', (data => {
console.log("net is unavailable, netId is " + data.netId); console.log("net is unavailable, netId is " + data.netId);
})); }));
// Register an observer for network status changes. // Register an observer for network status changes.
conn.register((err, data) => {}); conn.register((err, data) => {
});
// Unregister the observer for network status changes. // Unregister the observer for network status changes.
conn.unregister((err, data) => {}); conn.unregister((err, data) => {
});
``` ```
## Obtaining the List of All Registered Networks ## Obtaining the List of All Registered Networks
...@@ -120,16 +129,16 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -120,16 +129,16 @@ For the complete list of APIs and example code, see [Network Connection Manageme
```js ```js
// Import the connection namespace. // Import the connection namespace.
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
// Obtain the list of all connected networks. // Obtain the list of all connected networks.
connection.getAllNets((err, data) => { connection.getAllNets((err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
if (data) { if (data) {
this.netList = data; this.netList = data;
} }
}) })
``` ```
## Querying Network Capability Information and Connection Information of Specified Data Network ## Querying Network Capability Information and Connection Information of Specified Data Network
...@@ -146,19 +155,19 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -146,19 +155,19 @@ For the complete list of APIs and example code, see [Network Connection Manageme
```js ```js
// Import the connection namespace. // Import the connection namespace.
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
// Call getDefaultNet to obtain the default data network specified by **NetHandle**. // Call getDefaultNet to obtain the default data network specified by **NetHandle**.
connection.getDefaultNet((err, data) => { connection.getDefaultNet((err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
if (data) { if (data) {
this.netHandle = data; this.netHandle = data;
} }
}) })
// Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities. // Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities.
connection.getNetCapabilities(this.netHandle, (err, data) => { connection.getNetCapabilities(this.netHandle, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
// Obtain the network type via bearerTypes. // Obtain the network type via bearerTypes.
...@@ -194,24 +203,24 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -194,24 +203,24 @@ For the complete list of APIs and example code, see [Network Connection Manageme
console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); console.log(JSON.stringify("NET_CAPABILITY_VALIDATED"));
} }
} }
}) })
// Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information. // Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information.
connection.getConnectionProperties(this.netHandle, (err, data) => { connection.getConnectionProperties(this.netHandle, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
// Call getAllNets to obtain the list of all connected networks via Array<NetHandle>. // Call getAllNets to obtain the list of all connected networks via Array<NetHandle>.
connection.getAllNets((err, data) => { connection.getAllNets((err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
if (data) { if (data) {
this.netList = data; this.netList = data;
} }
}) })
for (let item of this.netList) { for (let item of this.netList) {
// Obtain the network capability information of the network specified by each netHandle on the network list cyclically. // Obtain the network capability information of the network specified by each netHandle on the network list cyclically.
connection.getNetCapabilities(item, (err, data) => { connection.getNetCapabilities(item, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
...@@ -223,7 +232,7 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -223,7 +232,7 @@ For the complete list of APIs and example code, see [Network Connection Manageme
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
} }
``` ```
## Resolving the domain name of a network to obtain all IP addresses ## Resolving the domain name of a network to obtain all IP addresses
...@@ -236,11 +245,11 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -236,11 +245,11 @@ For the complete list of APIs and example code, see [Network Connection Manageme
```js ```js
// Import the connection namespace. // Import the connection namespace.
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
// Use the default network to resolve the host name to obtain the list of all IP addresses. // Use the default network to resolve the host name to obtain the list of all IP addresses.
connection.getAddressesByName(this.host, (err, data) => { connection.getAddressesByName(this.host, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
``` ```
# Ethernet Connection # Ethernet Connection
## Introduction ## Introduction
The Ethernet Connection module allows a device to access the Internet through a network cable.
After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode. The Ethernet Connection module allows a device to access the Internet through a network cable. After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode.
> **NOTE** > **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md). > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md).
## **Constraints** ## **Constraints**
- Programming language: C++ and JS - Programming language: C++ and JS
- System: Linux kernel - System: Linux kernel
- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## When to Use ## When to Use
Typical application scenarios of Ethernet connection are as follows: Typical application scenarios of Ethernet connection are as follows:
- Dynamically assigning a series of network attributes, such as the IP address, subnet mask, gateway, and DNS in DHCP mode to enable network access - Dynamically assigning a series of network attributes, such as the IP address, subnet mask, gateway, and DNS in DHCP mode to enable network access
- Configuring a series of network attributes, such as the IP address, subnet mask, gateway, and DNS, in static mode to enable network access. - Configuring a series of network attributes, such as the IP address, subnet mask, gateway, and DNS, in static mode to enable network access.
The following describes the development procedure specific to each application scenario. The following describes the development procedure specific to each application scenario.
## Available APIs ## Available APIs
For the complete list of APIs and example code, see [Ethernet Connection](../reference/apis/js-apis-net-ethernet.md). For the complete list of APIs and example code, see [Ethernet Connection](../reference/apis/js-apis-net-ethernet.md).
| Type| API| Description| | Type| API| Description|
...@@ -28,6 +32,8 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ...@@ -28,6 +32,8 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref
| ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): void | Obtains the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.| | ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): void | Obtains the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function isIfaceActive(iface: string, callback: AsyncCallback\<number>): void | Checks whether the specified network port is active. This API uses an asynchronous callback to return the result.| | ohos.net.ethernet | function isIfaceActive(iface: string, callback: AsyncCallback\<number>): void | Checks whether the specified network port is active. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void; | Obtains the list of all active network ports. This API uses an asynchronous callback to return the result.| | ohos.net.ethernet | function getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void; | Obtains the list of all active network ports. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function on(type: 'interfaceStateChange', callback: Callback\<{ iface: string, active: boolean }\>): void; | Subscribes to interface state change events.|
| ohos.net.ethernet | function off(type: 'interfaceStateChange', callback?: Callback\<{ iface: string, active: boolean }\>): void; | Unsubscribes from interface state change events.|
## Ethernet Connection – DHCP Mode ## Ethernet Connection – DHCP Mode
...@@ -39,10 +45,10 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ...@@ -39,10 +45,10 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref
```js ```js
// Import the ethernet namespace from @ohos.net.ethernet. // Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet' import ethernet from '@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports. // Call getAllActiveIfaces to obtain the list of all active network ports.
ethernet.getAllActiveIfaces((error, data) => { ethernet.getAllActiveIfaces((error, data) => {
if (error) { if (error) {
console.log("getAllActiveIfaces callback error = " + error); console.log("getAllActiveIfaces callback error = " + error);
} else { } else {
...@@ -51,19 +57,19 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ...@@ -51,19 +57,19 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref
console.log("getAllActiveIfaces callback = " + data[i]); console.log("getAllActiveIfaces callback = " + data[i]);
} }
} }
}); });
// Call isIfaceActive to check whether the specified network port is active. // Call isIfaceActive to check whether the specified network port is active.
ethernet.isIfaceActive("eth0", (error, data) => { ethernet.isIfaceActive("eth0", (error, data) => {
if (error) { if (error) {
console.log("isIfaceActive callback error = " + error); console.log("isIfaceActive callback error = " + error);
} else { } else {
console.log("isIfaceActive callback = " + data); console.log("isIfaceActive callback = " + data);
} }
}); });
// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network. // Call getIfaceConfig to obtain the network attributes of the specified Ethernet network.
ethernet.getIfaceConfig("eth0", (error, data) => { ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) { if (error) {
console.log("getIfaceConfig callback error = " + error); console.log("getIfaceConfig callback error = " + error);
} else { } else {
...@@ -75,8 +81,9 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ...@@ -75,8 +81,9 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
} }
}); });
``` ```
## Ethernet Connection – Static Mode ## Ethernet Connection – Static Mode
### How to Develop ### How to Develop
...@@ -90,10 +97,10 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ...@@ -90,10 +97,10 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref
```js ```js
// Import the ethernet namespace from @ohos.net.ethernet. // Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet' import ethernet from '@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports. // Call getAllActiveIfaces to obtain the list of all active network ports.
ethernet.getAllActiveIfaces((error, data) => { ethernet.getAllActiveIfaces((error, data) => {
if (error) { if (error) {
console.log("getAllActiveIfaces callback error = " + error); console.log("getAllActiveIfaces callback error = " + error);
} else { } else {
...@@ -102,29 +109,31 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ...@@ -102,29 +109,31 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref
console.log("getAllActiveIfaces callback = " + data[i]); console.log("getAllActiveIfaces callback = " + data[i]);
} }
} }
}); });
// Call isIfaceActive to check whether the specified network port is active. // Call isIfaceActive to check whether the specified network port is active.
ethernet.isIfaceActive("eth0", (error, data) => { ethernet.isIfaceActive("eth0", (error, data) => {
if (error) { if (error) {
console.log("isIfaceActive callback error = " + error); console.log("isIfaceActive callback error = " + error);
} else { } else {
console.log("isIfaceActive callback = " + data); console.log("isIfaceActive callback = " + data);
} }
}); });
// Call setIfaceConfig to configure the network attributes of the specified Ethernet network. // Call setIfaceConfig to configure the network attributes of the specified Ethernet network.
ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx", ethernet.setIfaceConfig("eth0", {
gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"},(error) => { mode: ethernet.STATIC, ipAddr: "192.168.xx.xx", routeAddr: "192.168.xx.xx",
gateAddr: "192.168.xx.xx", maskAddr: "255.255.xx.xx", dnsAddr0: "1.1.xx.xx", dnsAddr1: "2.2.xx.xx"
}, (error) => {
if (error) { if (error) {
console.log("setIfaceConfig callback error = " + error); console.log("setIfaceConfig callback error = " + error);
} else { } else {
console.log("setIfaceConfig callback ok "); console.log("setIfaceConfig callback ok ");
} }
}); });
// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network. // Call getIfaceConfig to obtain the network attributes of the specified Ethernet network.
ethernet.getIfaceConfig("eth0", (error, data) => { ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) { if (error) {
console.log("getIfaceConfig callback error = " + error); console.log("getIfaceConfig callback error = " + error);
} else { } else {
...@@ -136,5 +145,27 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ...@@ -136,5 +145,27 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
} }
}); });
```
## Subscribes the status change of network device interfaces.
### How to Develop
1. Import the **ethernet** namespace from **@ohos.net.ethernet**.
2. Call the **on()** method to subscribe to **interfaceStateChange** events. It is up to you whether to listen for **interfaceStateChange** events.
3. Check whether an **interfaceStateChange** event is triggered when the interface state changes.
4. Call the **off()** method to unsubscribe from **interfaceStateChange** events.
```js
// Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet'
// Subscribe to interfaceStateChange events.
ethernet.on('interfaceStateChange', ((data) => {
console.log(JSON.stringify(data));
}));
// Unsubscribe from interfaceStateChange events.
ethernet.off('interfaceStateChange');
``` ```
# Network Sharing # Network Sharing
## Introduction ## Introduction
The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
> **NOTE** > **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md). > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md).
## Basic Concepts ## Basic Concepts
- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot. - Wi-Fi sharing: Shares the network through a Wi-Fi hotspot.
- Bluetooth sharing: Shares the network through Bluetooth. - Bluetooth sharing: Shares the network through Bluetooth.
- USB tethering: Shares the network using a USB flash drive. - USB tethering: Shares the network using a USB flash drive.
## **Constraints** ## **Constraints**
- Programming language: C++ and JS - Programming language: C++ and JS
- System: Linux kernel - System: Linux kernel
- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## When to Use ## When to Use
Typical network sharing scenarios are as follows: Typical network sharing scenarios are as follows:
- Enabling network sharing - Enabling network sharing
- Disabling network sharing - Disabling network sharing
- Obtaining the data traffic of the shared network - Obtaining the data traffic of the shared network
The following describes the development procedure specific to each application scenario. The following describes the development procedure specific to each application scenario.
## Available APIs ## Available APIs
For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md). For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md).
| Type| API| Description| | Type| API| Description|
...@@ -54,18 +61,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen ...@@ -54,18 +61,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js ```js
// Import the sharing namespace from @ohos.net.sharing. // Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes. // Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => { sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// Call startSharing to start network sharing of the specified type. // Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
## Disabling network sharing ## Disabling network sharing
...@@ -79,18 +86,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen ...@@ -79,18 +86,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js ```js
// Import the sharing namespace from @ohos.net.sharing. // Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes. // Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => { sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// Call stopSharing to stop network sharing of the specified type. // Call stopSharing to stop network sharing of the specified type.
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
## Obtaining the data traffic of the shared network ## Obtaining the data traffic of the shared network
...@@ -104,27 +111,27 @@ For the complete list of APIs and example code, see [Network Sharing](../referen ...@@ -104,27 +111,27 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js ```js
// Import the sharing namespace from @ohos.net.sharing. // Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type. // Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
// Call getStatsTotalBytes to obtain the data traffic generated during data sharing. // Call getStatsTotalBytes to obtain the data traffic generated during data sharing.
sharing.getStatsTotalBytes((error, data) => { sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing. // Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing.
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
// Call getStatsTotalBytes again. The data volume of network sharing has been cleared. // Call getStatsTotalBytes again. The data volume of network sharing has been cleared.
sharing.getStatsTotalBytes((error, data) => { sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -186,11 +186,11 @@ TLS Socket connection process on the client: ...@@ -186,11 +186,11 @@ TLS Socket connection process on the client:
```js ```js
import socket from '@ohos.net.socket' import socket from '@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication). // Create a TLS Socket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance(); let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events. // Subscribe to TLS Socket connection events.
tlsTwoWay.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
...@@ -199,25 +199,25 @@ TLS Socket connection process on the client: ...@@ -199,25 +199,25 @@ TLS Socket connection process on the client:
str += String.fromCharCode(dataView.getUint8(i)) str += String.fromCharCode(dataView.getUint8(i))
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tlsTwoWay.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tlsTwoWay.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
// Bind the local IP address and port number. // Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
} }
console.log('bind success'); console.log('bind success');
}); });
// Set the communication parameters. // Set the communication parameters.
let options = { let options = {
ALPNProtocols: ["spdy/1", "http/1.1"], ALPNProtocols: ["spdy/1", "http/1.1"],
// Set up a connection to the specified IP address and port number. // Set up a connection to the specified IP address and port number.
...@@ -238,16 +238,16 @@ TLS Socket connection process on the client: ...@@ -238,16 +238,16 @@ TLS Socket connection process on the client:
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm
cipherSuite: "AES256-SHA256", // Cipher suite cipherSuite: "AES256-SHA256", // Cipher suite
}, },
}; };
// Set up a connection. // Set up a connection.
tlsTwoWay.connect(options, (err, data) => { tlsTwoWay.connect(options, (err, data) => {
console.error(err); console.error(err);
console.log(data); console.log(data);
}); });
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
...@@ -256,40 +256,40 @@ TLS Socket connection process on the client: ...@@ -256,40 +256,40 @@ TLS Socket connection process on the client:
tlsTwoWay.off('message'); tlsTwoWay.off('message');
tlsTwoWay.off('connect'); tlsTwoWay.off('connect');
tlsTwoWay.off('close'); tlsTwoWay.off('close');
}); });
// Create a TLS Socket connection (for one-way authentication). // Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events. // Subscribe to TLS Socket connection events.
tlsTwoWay.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
let str = "" let str = ""
for (let i = 0;i < dataView.byteLength; ++i) { for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i)) str += String.fromCharCode(dataView.getUint8(i))
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tlsTwoWay.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tlsTwoWay.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
// Bind the local IP address and port number. // Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
} }
console.log('bind success'); console.log('bind success');
}); });
// Set the communication parameters. // Set the communication parameters.
let oneWayOptions = { let oneWayOptions = {
address: { address: {
address: "192.168.xxx.xxx", address: "192.168.xxx.xxx",
port: xxxx, port: xxxx,
...@@ -299,16 +299,16 @@ TLS Socket connection process on the client: ...@@ -299,16 +299,16 @@ TLS Socket connection process on the client:
ca: ["xxxx","xxxx"], // CA certificate ca: ["xxxx","xxxx"], // CA certificate
cipherSuite: "AES256-SHA256", // Cipher suite cipherSuite: "AES256-SHA256", // Cipher suite
}, },
}; };
// Set up a connection. // Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => { tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err); console.error(err);
console.log(data); console.log(data);
}); });
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
...@@ -317,5 +317,5 @@ TLS Socket connection process on the client: ...@@ -317,5 +317,5 @@ TLS Socket connection process on the client:
tlsTwoWay.off('message'); tlsTwoWay.off('message');
tlsTwoWay.off('connect'); tlsTwoWay.off('connect');
tlsTwoWay.off('close'); tlsTwoWay.off('close');
}); });
``` ```
\ No newline at end of file
# WebSocket Connection # WebSocket Connection
## When to Use
## Use Cases
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event. You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event. If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event.
## Available APIs ## Available APIs
The WebSocket connection function is mainly implemented by the WebSocket module. To use related APIs, you must declare the **ohos.permission.INTERNET** permission. The following table describes the related APIs. The WebSocket connection function is mainly implemented by the WebSocket module. To use related APIs, you must declare the **ohos.permission.INTERNET** permission. The following table describes the related APIs.
| API | Description | | API| Description|
| -------- | -------- | | -------- | -------- |
| createWebSocket() | Creates a WebSocket connection. | | createWebSocket() | Creates a WebSocket connection.|
| connect() | Establishes a WebSocket connection to a given URL. | | connect() | Establishes a WebSocket connection to a given URL.|
| send() | Sends data through the WebSocket connection. | | send() | Sends data through the WebSocket connection.|
| close() | Closes a WebSocket connection. | | close() | Closes a WebSocket connection.|
| on(type: 'open') | Enables listening for **open** events of a WebSocket connection. | | on(type: 'open') | Enables listening for **open** events of a WebSocket connection.|
| off(type: 'open') | Disables listening for **open** events of a WebSocket connection. | | off(type: 'open') | Disables listening for **open** events of a WebSocket connection.|
| on(type: 'message') | Enables listening for **message** events of a WebSocket connection. | | on(type: 'message') | Enables listening for **message** events of a WebSocket connection.|
| off(type: 'message') | Disables listening for **message** events of a WebSocket connection. | | off(type: 'message') | Disables listening for **message** events of a WebSocket connection.|
| on(type: 'close') | Enables listening for **close** events of a WebSocket connection. | | on(type: 'close') | Enables listening for **close** events of a WebSocket connection.|
| off(type: 'close') | Disables listening for **close** events of a WebSocket connection. | | off(type: 'close') | Disables listening for **close** events of a WebSocket connection.|
| on(type: 'error') | Enables listening for **error** events of a WebSocket connection. | | on(type: 'error') | Enables listening for **error** events of a WebSocket connection.|
| off(type: 'error') | Disables listening for **error** events of a WebSocket connection. | | off(type: 'error') | Disables listening for **error** events of a WebSocket connection.|
## How to Develop ## How to Develop
1. Import the required WebSocket module. 1. Import the required webSocket module.
2. Create a **WebSocket** object. 2. Create a **WebSocket** object.
3. (Optional) Subscribe to WebSocket open, message, close, and error events. 3. (Optional) Subscribe to WebSocket **open**, **message**, **close**, and **error** events.
4. Establish a WebSocket connection to a given URL. 4. Establish a WebSocket connection to a given URL.
......
...@@ -173,7 +173,7 @@ Obtains system service information. ...@@ -173,7 +173,7 @@ Obtains system service information.
**Example** **Example**
```js ```js
import fileio from '@ohos.fileio' import fs from '@ohos.file.fs'
import hidebug from '@ohos.hidebug' import hidebug from '@ohos.hidebug'
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
...@@ -181,7 +181,7 @@ let context = featureAbility.getContext(); ...@@ -181,7 +181,7 @@ let context = featureAbility.getContext();
context.getFilesDir().then((data) => { context.getFilesDir().then((data) => {
var path = data + "/serviceInfo.txt" var path = data + "/serviceInfo.txt"
console.info("output path: " + path) console.info("output path: " + path)
let fd = fileio.openSync(path, 0o102, 0o666) let fd = fs.openSync(path, 0o102, 0o666)
var serviceId = 10 var serviceId = 10
var args = new Array("allInfo") var args = new Array("allInfo")
try { try {
...@@ -190,7 +190,7 @@ context.getFilesDir().then((data) => { ...@@ -190,7 +190,7 @@ context.getFilesDir().then((data) => {
console.info(error.code) console.info(error.code)
console.info(error.message) console.info(error.message)
} }
fileio.closeSync(fd); fs.closeSync(fd);
}) })
``` ```
...@@ -283,7 +283,7 @@ try { ...@@ -283,7 +283,7 @@ try {
startProfiling(filename : string) : void startProfiling(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9) instead. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9).
Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
...@@ -309,7 +309,7 @@ hidebug.stopProfiling(); ...@@ -309,7 +309,7 @@ hidebug.stopProfiling();
stopProfiling() : void stopProfiling() : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9) instead. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9).
Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
...@@ -329,7 +329,7 @@ hidebug.stopProfiling(); ...@@ -329,7 +329,7 @@ hidebug.stopProfiling();
dumpHeapData(filename : string) : void dumpHeapData(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9) instead. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9).
Exports the heap data. Exports the heap data.
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
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**. 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**.
>**NOTE** > **NOTE**
> >
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. >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.
> >
...@@ -35,11 +35,11 @@ httpRequest.request( ...@@ -35,11 +35,11 @@ httpRequest.request(
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
// This field is used to transfer data when the POST request is used. // This parameter is used to transfer data when the POST request is used.
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data.
usingCache: true, // Optional. The default value is true. usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1. priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms. connectTimeout: 60000 // Optional. The default value is 60000, in ms.
...@@ -83,6 +83,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req ...@@ -83,6 +83,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req
```js ```js
import http from '@ohos.net.http'; import http from '@ohos.net.http';
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
``` ```
...@@ -96,8 +97,8 @@ request(url: string, callback: AsyncCallback\<HttpResponse\>):void ...@@ -96,8 +97,8 @@ 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. Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API supports only transfer of data not greater than 5 MB. > This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -122,7 +123,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ...@@ -122,7 +123,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
| 2300052 | Server returned nothing (no headers, no data). | | 2300052 | Server returned nothing (no headers, no data). |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**NOTE** > **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > 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). > 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).
...@@ -147,8 +148,8 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR ...@@ -147,8 +148,8 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API supports only transfer of data not greater than 5 MB. > This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -198,7 +199,7 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -198,7 +199,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
| 2300094 | An authentication function returned an error. | | 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**NOTE** > **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > 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). > 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).
...@@ -206,14 +207,14 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -206,14 +207,14 @@ Initiates an HTTP request containing specified options to a given URL. This API
```js ```js
httpRequest.request("EXAMPLE_URL", httpRequest.request("EXAMPLE_URL",
{ {
method: http.RequestMethod.GET, method: http.RequestMethod.GET,
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
readTimeout: 60000, readTimeout: 60000,
connectTimeout: 60000 connectTimeout: 60000
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
console.info('Result:' + data.result); console.info('Result:' + data.result);
console.info('code:' + data.responseCode); console.info('code:' + data.responseCode);
...@@ -224,7 +225,7 @@ httpRequest.request("EXAMPLE_URL", ...@@ -224,7 +225,7 @@ httpRequest.request("EXAMPLE_URL",
} else { } else {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
} }
}); });
``` ```
### request ### request
...@@ -233,8 +234,8 @@ request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\> ...@@ -233,8 +234,8 @@ request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result.
>**NOTE** > **NOTE**
>This API supports only transfer of data not greater than 5 MB. > This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -289,7 +290,7 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -289,7 +290,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
| 2300094 | An authentication function returned an error. | | 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**NOTE** > **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > 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). > 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).
...@@ -334,7 +335,7 @@ httpRequest.destroy(); ...@@ -334,7 +335,7 @@ httpRequest.destroy();
request2(url: string, callback: AsyncCallback\<number\>): void request2(url: string, callback: AsyncCallback\<number\>): void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. 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.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -359,7 +360,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ...@@ -359,7 +360,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
| 2300052 | Server returned nothing (no headers, no data). | | 2300052 | Server returned nothing (no headers, no data). |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**NOTE** > **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > 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). > 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).
...@@ -429,7 +430,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ...@@ -429,7 +430,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
| 2300094 | An authentication function returned an error. | | 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**NOTE** > **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > 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). > 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).
...@@ -437,21 +438,22 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ...@@ -437,21 +438,22 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
```js ```js
httpRequest.request2("EXAMPLE_URL", httpRequest.request2("EXAMPLE_URL",
{ {
method: http.RequestMethod.GET, method: http.RequestMethod.GET,
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
readTimeout: 60000, readTimeout: 60000,
connectTimeout: 60000 connectTimeout: 60000
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
console.info("request2 OK! ResponseCode is " + JSON.stringify(data)); console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
} else { } else {
console.info("request2 ERROR : err = " + JSON.stringify(err)); console.info("request2 ERROR : err = " + JSON.stringify(err));
} }
}) })
``` ```
### request2<sup>10+</sup> ### request2<sup>10+</sup>
request2(url: string, options? : HttpRequestOptions): Promise\<number\> request2(url: string, options? : HttpRequestOptions): Promise\<number\>
...@@ -472,7 +474,7 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -472,7 +474,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Return value** **Return value**
| Type | Description | | Type | Description |
| :------------------------------------- | :-------------------------------- | | ------------------------------------- | -------------------------------- |
| Promise\<[number](#responsecode)\> | Promise used to return the result.| | Promise\<[number](#responsecode)\> | Promise used to return the result.|
**Error codes** **Error codes**
...@@ -511,14 +513,14 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -511,14 +513,14 @@ Initiates an HTTP request containing specified options to a given URL. This API
| 2300094 | An authentication function returned an error. | | 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**NOTE** > **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > 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). > 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** **Example**
```js ```js
let promise = httpRequest.request("EXAMPLE_URL", { let promise = httpRequest.request2("EXAMPLE_URL", {
method: http.RequestMethod.GET, method: http.RequestMethod.GET,
connectTimeout: 60000, connectTimeout: 60000,
readTimeout: 60000, readTimeout: 60000,
...@@ -539,8 +541,8 @@ on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void ...@@ -539,8 +541,8 @@ on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void
Registers an observer for HTTP Response Header events. Registers an observer for HTTP Response Header events.
>**NOTE** > **NOTE**
>This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8). > This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8).
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -565,7 +567,7 @@ off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void ...@@ -565,7 +567,7 @@ off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>**NOTE** > **NOTE**
> >
>1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8). >1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8).
> >
...@@ -615,8 +617,8 @@ off(type: 'headersReceive', callback?: Callback\<Object\>): void ...@@ -615,8 +617,8 @@ off(type: 'headersReceive', callback?: Callback\<Object\>): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>**NOTE** > **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. > 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 **System capability**: SystemCapability.Communication.NetStack
...@@ -655,6 +657,7 @@ httpRequest.once('headersReceive', (header) => { ...@@ -655,6 +657,7 @@ httpRequest.once('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
``` ```
### on('dataReceive')<sup>10+</sup> ### on('dataReceive')<sup>10+</sup>
on(type: 'dataReceive', callback: Callback\<ArrayBuffer\>): void on(type: 'dataReceive', callback: Callback\<ArrayBuffer\>): void
...@@ -684,8 +687,8 @@ off(type: 'dataReceive', callback?: Callback\<ArrayBuffer\>): void ...@@ -684,8 +687,8 @@ off(type: 'dataReceive', callback?: Callback\<ArrayBuffer\>): void
Unregisters the observer for events indicating receiving of HTTP streaming responses. Unregisters the observer for events indicating receiving of HTTP streaming responses.
>**NOTE** > **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. > 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 **System capability**: SystemCapability.Communication.NetStack
...@@ -720,8 +723,8 @@ Registers an observer for events indicating completion of receiving HTTP streami ...@@ -720,8 +723,8 @@ Registers an observer for events indicating completion of receiving HTTP streami
**Example** **Example**
```js ```js
httpRequest.on('dataReceive', () => { httpRequest.on('dataEnd', () => {
console.info('Receive dataEnd! '); console.info('Receive dataEnd !');
}); });
``` ```
...@@ -731,8 +734,8 @@ off(type: 'dataEnd', callback?: Callback\<void\>): void ...@@ -731,8 +734,8 @@ off(type: 'dataEnd', callback?: Callback\<void\>): void
Unregisters the observer for events indicating completion of receiving HTTP streaming responses. Unregisters the observer for events indicating completion of receiving HTTP streaming responses.
>**NOTE** > **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. > 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 **System capability**: SystemCapability.Communication.NetStack
...@@ -751,7 +754,7 @@ httpRequest.off('dataEnd'); ...@@ -751,7 +754,7 @@ httpRequest.off('dataEnd');
### on('dataProgress')<sup>10+</sup> ### on('dataProgress')<sup>10+</sup>
on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void on(type: 'dataProgress', callback: AsyncCallback\<{ receiveSize: number, totalSize: number }\>): void
Registers an observer for events indicating progress of receiving HTTP streaming responses. Registers an observer for events indicating progress of receiving HTTP streaming responses.
...@@ -762,7 +765,7 @@ Registers an observer for events indicating progress of receiving HTTP streaming ...@@ -762,7 +765,7 @@ Registers an observer for events indicating progress of receiving HTTP streaming
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | --------------------------------- | | -------- | ----------------------- | ---- | --------------------------------- |
| type | string | Yes | Event type. The value is **dataProgress**.| | type | string | Yes | Event type. The value is **dataProgress**.|
| 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.| | 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.|
**Example** **Example**
...@@ -778,8 +781,8 @@ off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: ...@@ -778,8 +781,8 @@ off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize:
Unregisters the observer for events indicating progress of receiving HTTP streaming responses. Unregisters the observer for events indicating progress of receiving HTTP streaming responses.
>**NOTE** > **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. > 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 **System capability**: SystemCapability.Communication.NetStack
...@@ -795,6 +798,7 @@ Unregisters the observer for events indicating progress of receiving HTTP stream ...@@ -795,6 +798,7 @@ Unregisters the observer for events indicating progress of receiving HTTP stream
```js ```js
httpRequest.off('dataProgress'); httpRequest.off('dataProgress');
``` ```
## HttpRequestOptions ## HttpRequestOptions
Specifies the type and value range of the optional parameters in the HTTP request. Specifies the type and value range of the optional parameters in the HTTP request.
...@@ -803,11 +807,11 @@ Specifies the type and value range of the optional parameters in the HTTP reques ...@@ -803,11 +807,11 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. | | method | [RequestMethod](#requestmethod) | No | Request method. The default value is **GET**. |
| extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>6+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>6+</sup> | | 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.<sup>6+</sup><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.<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the return data. If this parameter is set, the system returns the specified type of data preferentially.| | 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.|
| usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. | | usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. |
| priority<sup>9+</sup> | number | No | Priority. The value range is \[1,1000]. The default value is **1**. | | priority<sup>9+</sup> | number | No | Priority. The value range is \[0, 1000]. The default value is **0**. |
| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | 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. | | 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. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
...@@ -883,10 +887,10 @@ Defines the response to an HTTP request. ...@@ -883,10 +887,10 @@ Defines the response to an HTTP request.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string| | 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|
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. | | resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. |
| 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**.| | 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**.|
| 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'];| | 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> | string | Yes | Cookies returned by the server. | | cookies<sup>8+</sup> | string | Yes | Cookies returned by the server. |
## http.createHttpResponseCache<sup>9+</sup> ## http.createHttpResponseCache<sup>9+</sup>
...@@ -913,6 +917,7 @@ Creates a default object to store responses to HTTP access requests. ...@@ -913,6 +917,7 @@ Creates a default object to store responses to HTTP access requests.
```js ```js
import http from '@ohos.net.http'; import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache(); let httpResponseCache = http.createHttpResponseCache();
``` ```
...@@ -995,6 +1000,7 @@ httpResponseCache.delete(err => { ...@@ -995,6 +1000,7 @@ httpResponseCache.delete(err => {
console.info('delete success'); console.info('delete success');
}); });
``` ```
### delete<sup>9+</sup> ### delete<sup>9+</sup>
delete(): Promise\<void\> delete(): Promise\<void\>
......
...@@ -10,6 +10,7 @@ The network connection management module provides basic network management capab ...@@ -10,6 +10,7 @@ The network connection management module provides basic network management capab
```js ```js
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
``` ```
## connection.createNetConnection ## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
...@@ -34,10 +35,10 @@ Creates a **NetConnection** object. **netSpecifier** specifies the network, and ...@@ -34,10 +35,10 @@ Creates a **NetConnection** object. **netSpecifier** specifies the network, and
**Example** **Example**
```js ```js
// Default network // For the default network, you do not need to pass in parameters.
let netConnection = connection.createNetConnection() let netConnection = connection.createNetConnection()
// Cellular network // For the cellular network, you need to pass in related network parameters. If the timeout parameter is not specified, the timeout value is 0 by default.
let netConnectionCellular = connection.createNetConnection({ let netConnectionCellular = connection.createNetConnection({
netCapabilities: { netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR] bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
...@@ -166,7 +167,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy ...@@ -166,7 +167,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy
**Example** **Example**
```js ```js
connection.getGlobalHttpProxy((error,data) => { connection.getGlobalHttpProxy((error, data) => {
console.info(JSON.stringify(error)); console.info(JSON.stringify(error));
console.info(JSON.stringify(data)); console.info(JSON.stringify(data));
}) })
...@@ -237,16 +238,15 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch ...@@ -237,16 +238,15 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch
**Example** **Example**
```js ```js
let exclusionStr="192.168,baidu.com" let exclusionStr = "192.168,baidu.com"
let exclusionArray = exclusionStr.split(','); let exclusionArray = exclusionStr.split(',');
let httpProxy = { let httpProxy = {
host: "192.168.xx.xxx", host: "192.168.xx.xxx",
port: 8080, port: 8080,
exclusionList: exclusionArray exclusionList: exclusionArray
} }
connection.setGlobalHttpProxy(httpProxy, (error, data) => { connection.setGlobalHttpProxy(httpProxy, (error) => {
console.info(JSON.stringify(error)); console.info(JSON.stringify(error));
console.info(JSON.stringify(data));
}); });
``` ```
...@@ -287,7 +287,7 @@ Sets the global HTTP proxy configuration of the network. This API uses a promise ...@@ -287,7 +287,7 @@ Sets the global HTTP proxy configuration of the network. This API uses a promise
**Example** **Example**
```js ```js
let exclusionStr="192.168,baidu.com" let exclusionStr = "192.168,baidu.com"
let exclusionArray = exclusionStr.split(','); let exclusionArray = exclusionStr.split(',');
let httpProxy = { let httpProxy = {
host: "192.168.xx.xxx", host: "192.168.xx.xxx",
...@@ -296,7 +296,7 @@ let httpProxy = { ...@@ -296,7 +296,7 @@ let httpProxy = {
} }
connection.setGlobalHttpProxy(httpProxy).then(() => { connection.setGlobalHttpProxy(httpProxy).then(() => {
console.info("success"); console.info("success");
}).catch(error=>{ }).catch(error => {
console.info(JSON.stringify(error)); console.info(JSON.stringify(error));
}) })
``` ```
...@@ -325,7 +325,7 @@ Obtains information about the network bound to an application. This API uses an ...@@ -325,7 +325,7 @@ Obtains information about the network bound to an application. This API uses an
**Example** **Example**
```js ```js
connection.getAppNet(function(error, data) { connection.getAppNet(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -935,8 +935,7 @@ connection.disableAirplaneMode().then(function (error) { ...@@ -935,8 +935,7 @@ connection.disableAirplaneMode().then(function (error) {
reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. Reports connection of the data network to the network management module. This API uses an asynchronous callback to return the result.
This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -973,8 +972,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -973,8 +972,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. Reports connection of the data network to the network management module. This API uses a promise to return the result.
This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -1015,8 +1013,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -1015,8 +1013,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. Reports disconnection of the data network to the network management module. This API uses an asynchronous callback to return the result.
This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -1053,8 +1050,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -1053,8 +1050,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. Reports disconnection of the data network to the network management module. This API uses a promise to return the result.
This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -1173,6 +1169,11 @@ connection.getAddressesByName(host).then(function (data) { ...@@ -1173,6 +1169,11 @@ connection.getAddressesByName(host).then(function (data) {
Represents the network connection handle. Represents the network connection handle.
> **NOTE**
> When a device changes to the network connected state, the **netAvailable**, **netCapabilitiesChange**, and **netConnectionPropertiesChange** events will be triggered.
> When a device changes to the network disconnected state, the **netLost** event will be triggered.
> When a device switches from a Wi-Fi network to a cellular network, the **netLost** event will be first triggered to indicate that the Wi-Fi network is lost and then the **netAvaliable** event will be triggered to indicate that the cellular network is available.
### register ### register
register(callback: AsyncCallback\<void>): void register(callback: AsyncCallback\<void>): void
...@@ -1199,7 +1200,6 @@ Registers a listener for network status changes. ...@@ -1199,7 +1200,6 @@ Registers a listener for network status changes.
| 2101008 | The callback is not exists. | | 2101008 | The callback is not exists. |
| 2101022 | The number of requests exceeded the maximum. | | 2101022 | The number of requests exceeded the maximum. |
**Example** **Example**
```js ```js
...@@ -1281,9 +1281,9 @@ netCon.unregister(function (error) { ...@@ -1281,9 +1281,9 @@ netCon.unregister(function (error) {
on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, blocked: boolean }&gt;): void on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, blocked: boolean }&gt;): void
Registers a listener for **netBlockStatusChange** events. Registers a listener for **netBlockStatusChange** events. This API uses an asynchronous callback to return the result.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network. **Model restriction**: Before you call this API, make sure that you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
...@@ -1357,7 +1357,8 @@ netCon.unregister(function (error) { ...@@ -1357,7 +1357,8 @@ netCon.unregister(function (error) {
### on('netConnectionPropertiesChange') ### on('netConnectionPropertiesChange')
on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties:
ConnectionProperties }>): void
Registers a listener for **netConnectionPropertiesChange** events. Registers a listener for **netConnectionPropertiesChange** events.
...@@ -1370,7 +1371,7 @@ Registers a listener for **netConnectionPropertiesChange** events. ...@@ -1370,7 +1371,7 @@ Registers a listener for **netConnectionPropertiesChange** events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| | type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).| | callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and connection information (**connectionProperties**).|
**Example** **Example**
...@@ -1514,6 +1515,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -1514,6 +1515,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
```js ```js
import socket from "@ohos.net.socket"; import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle) => { connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
...@@ -1524,6 +1526,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1524,6 +1526,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
netHandle.bindSocket(tcp, (error, data) => { netHandle.bindSocket(tcp, (error, data) => {
if (error) { if (error) {
...@@ -1543,6 +1546,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1543,6 +1546,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
...@@ -1592,6 +1596,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -1592,6 +1596,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
```js ```js
import socket from "@ohos.net.socket"; import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle) => { connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
...@@ -1602,6 +1607,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1602,6 +1607,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
netHandle.bindSocket(tcp).then((data) => { netHandle.bindSocket(tcp).then((data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
...@@ -1619,6 +1625,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1619,6 +1625,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
...@@ -1905,8 +1912,8 @@ Defines a network address. ...@@ -1905,8 +1912,8 @@ Defines a network address.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory| Description | | Name| Type| Mandatory| Description|
| ------- | ------ | -- |------------------------------ | | ------- | ------ | -- |------------------------------ |
| address | string | Yes|Network address. | | address | string | Yes|Network address.|
| family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| | family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.|
| port | number | No|Port number. The value ranges from **0** to **65535**. | | port | number | No|Port number. The value ranges from **0** to **65535**.|
...@@ -386,6 +386,74 @@ ethernet.getAllActiveIfaces().then((data) => { ...@@ -386,6 +386,74 @@ ethernet.getAllActiveIfaces().then((data) => {
}); });
``` ```
## ethernet.on('interfaceStateChange')<sup>10+</sup>
on(type: 'interfaceStateChange', callback: Callback\<{ iface: string, active: boolean }\>): void
Registers an observer for NIC hot swap events. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| type | string | Yes | Event type. The value is **interfaceStateChange**.|
| callback | AsyncCallback\<{ iface: string, active: boolean }\> | Yes | Callback used to return the result.<br>**iface**: NIC name.<br>**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Applicable only to system applications. |
| 401 | Parameter error. |
**Example**
```js
ethernet.on('interfaceStateChange', (data) => {
console.log('on interfaceSharingStateChange: ' + JSON.stringify(data));
});
```
## ethernet.off('interfaceStateChange')<sup>10+</sup>
off(type: 'interfaceStateChange', callback?: Callback\<{ iface: string, active: boolean }\>): void
Unregisters the observer for NIC hot swap events. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| type | string | Yes | Event type. The value is **interfaceStateChange**.|
| callback | AsyncCallback\<{ iface: string, active: boolean }> | No | Callback used to return the result.<br>**iface**: NIC name.<br>**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Applicable only to system applications. |
| 401 | Parameter error. |
**Example**
```js
ethernet.off('interfaceStateChange');
```
## InterfaceConfiguration ## InterfaceConfiguration
Defines the network configuration for the Ethernet connection. Defines the network configuration for the Ethernet connection.
......
...@@ -46,7 +46,9 @@ policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, da ...@@ -46,7 +46,9 @@ policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, da
this.callBack(error, data); this.callBack(error, data);
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); }
)
;
``` ```
## policy.setBackgroundPolicy ## policy.setBackgroundPolicy
...@@ -84,7 +86,7 @@ Sets a background network policy. This API uses a promise to return the result. ...@@ -84,7 +86,7 @@ Sets a background network policy. This API uses a promise to return the result.
**Example** **Example**
```js ```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -151,7 +153,7 @@ Obtains the background network policy. This API uses a promise to return the res ...@@ -151,7 +153,7 @@ Obtains the background network policy. This API uses a promise to return the res
**Example** **Example**
```js ```js
policy.isBackgroundAllowed().then(function(error, data) { policy.isBackgroundAllowed().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -236,7 +238,7 @@ Sets an application-specific network policy. This API uses a promise to return t ...@@ -236,7 +238,7 @@ Sets an application-specific network policy. This API uses a promise to return t
let param = { let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
} }
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function(error, data) { policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -313,7 +315,7 @@ Obtains an application-specific network policy by **uid**. This API uses a promi ...@@ -313,7 +315,7 @@ Obtains an application-specific network policy by **uid**. This API uses a promi
**Example** **Example**
```js ```js
policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -390,7 +392,7 @@ Obtains the UID array of applications configured with a certain application-spec ...@@ -390,7 +392,7 @@ Obtains the UID array of applications configured with a certain application-spec
**Example** **Example**
```js ```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -456,7 +458,7 @@ Obtains the network quota policies. This API uses a promise to return the result ...@@ -456,7 +458,7 @@ Obtains the network quota policies. This API uses a promise to return the result
**Example** **Example**
```js ```js
policy.getNetQuotaPolicies().then(function(error, data) { policy.getNetQuotaPolicies().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -493,8 +495,18 @@ Sets an array of network quota policies. This API uses an asynchronous callback ...@@ -493,8 +495,18 @@ Sets an array of network quota policies. This API uses an asynchronous callback
**Example** **Example**
```js ```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), let param = {
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; netType: Number.parseInt(this.netType),
iccid: this.iccid,
ident: this.ident,
periodDuration: this.periodDuration,
warningBytes: Number.parseInt(this.warningBytes),
limitBytes: Number.parseInt(this.limitBytes),
lastWarningRemind: this.lastWarningRemind,
lastLimitRemind: this.lastLimitRemind,
metered: Boolean(Number.parseInt(this.metered)),
limitAction: this.limitAction
};
this.netQuotaPolicyList.push(param); this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => { policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => {
...@@ -537,11 +549,21 @@ Sets an array of network quota policies. This API uses a promise to return the r ...@@ -537,11 +549,21 @@ Sets an array of network quota policies. This API uses a promise to return the r
**Example** **Example**
```js ```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), let param = {
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; netType: Number.parseInt(this.netType),
iccid: this.iccid,
ident: this.ident,
periodDuration: this.periodDuration,
warningBytes: Number.parseInt(this.warningBytes),
limitBytes: Number.parseInt(this.limitBytes),
lastWarningRemind: this.lastWarningRemind,
lastLimitRemind: this.lastLimitRemind,
metered: Boolean(Number.parseInt(this.metered)),
limitAction: this.limitAction
};
this.netQuotaPolicyList.push(param); this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) { policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -619,7 +641,7 @@ Restores all the policies (cellular network, background network, firewall, and a ...@@ -619,7 +641,7 @@ Restores all the policies (cellular network, background network, firewall, and a
```js ```js
this.firstParam = iccid; this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam).then(function(error, data){ policy.restoreAllPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -706,7 +728,7 @@ Checks whether an application is allowed to access metered networks. This API us ...@@ -706,7 +728,7 @@ Checks whether an application is allowed to access metered networks. This API us
let param = { let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -792,7 +814,7 @@ Checks whether an application is allowed to access the given network. This API u ...@@ -792,7 +814,7 @@ Checks whether an application is allowed to access the given network. This API u
let param = { let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam uid: Number.parseInt(this.firstParam), iface: this.secondParam
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function(error, data) { policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -877,7 +899,7 @@ Sets whether to add an application to the device idle allowlist. This API uses a ...@@ -877,7 +899,7 @@ Sets whether to add an application to the device idle allowlist. This API uses a
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -943,7 +965,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi ...@@ -943,7 +965,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
**Example** **Example**
```js ```js
policy.getDeviceIdleAllowList().then(function(error, data) { policy.getDeviceIdleAllowList().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1021,7 +1043,7 @@ Obtains the background network policies configured for the given application. Th ...@@ -1021,7 +1043,7 @@ Obtains the background network policies configured for the given application. Th
```js ```js
this.firstParam = uid this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1098,11 +1120,11 @@ Restores all the policies (cellular network, background network, firewall, and a ...@@ -1098,11 +1120,11 @@ Restores all the policies (cellular network, background network, firewall, and a
**Example** **Example**
```js ```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
}) })
this.firstParam = iccid this.firstParam = iccid
policy.resetPolicies(this.firstParam).then(function(error, data) { policy.resetPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1189,7 +1211,7 @@ Updates a reminder policy. This API uses a promise to return the result. ...@@ -1189,7 +1211,7 @@ Updates a reminder policy. This API uses a promise to return the result.
let param = { let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
} }
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function(error, data) { policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1274,7 +1296,7 @@ Sets whether to add an application to the power-saving allowlist. This API uses ...@@ -1274,7 +1296,7 @@ Sets whether to add an application to the power-saving allowlist. This API uses
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1340,7 +1362,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi ...@@ -1340,7 +1362,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
**Example** **Example**
```js ```js
policy.getPowerSaveAllowList().then(function(error, data) { policy.getPowerSaveAllowList().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1540,7 +1562,7 @@ Enumerates the reminder types. ...@@ -1540,7 +1562,7 @@ Enumerates the reminder types.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value| Description | | Name| Value| Description|
| ---------------------- | - | ------- | | ---------------------- | - | ------- |
| REMIND_TYPE_WARNING | 1 | Warning.| | REMIND_TYPE_WARNING | 1 | Warning.|
| REMIND_TYPE_LIMIT | 2 | Limit.| | REMIND_TYPE_LIMIT | 2 | Limit.|
......
...@@ -194,7 +194,8 @@ Starts network sharing of a specified type. This API uses an asynchronous callba ...@@ -194,7 +194,8 @@ Starts network sharing of a specified type. This API uses an asynchronous callba
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI, (error) => { sharing.startSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
...@@ -243,7 +244,8 @@ Starts network sharing of a specified type. This API uses a promise to return th ...@@ -243,7 +244,8 @@ Starts network sharing of a specified type. This API uses a promise to return th
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI).then(() => { sharing.startSharing(SHARING_WIFI).then(() => {
console.log("start wifi sharing successful"); console.log("start wifi sharing successful");
}).catch(error => { }).catch(error => {
...@@ -287,7 +289,8 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac ...@@ -287,7 +289,8 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI, (error) => { sharing.stopSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
...@@ -334,7 +337,8 @@ Stops network sharing of a specified type. This API uses a promise to return the ...@@ -334,7 +337,8 @@ Stops network sharing of a specified type. This API uses a promise to return the
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI).then(() => { sharing.stopSharing(SHARING_WIFI).then(() => {
console.log("stop wifi sharing successful"); console.log("stop wifi sharing successful");
}).catch(error => { }).catch(error => {
...@@ -588,7 +592,8 @@ Obtains the names of NICs in the specified network sharing state. This API uses ...@@ -588,7 +592,8 @@ Obtains the names of NICs in the specified network sharing state. This API uses
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => { sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
...@@ -633,7 +638,8 @@ Obtains the names of NICs in the specified network sharing state. This API uses ...@@ -633,7 +638,8 @@ Obtains the names of NICs in the specified network sharing state. This API uses
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => { sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
...@@ -674,7 +680,8 @@ Obtains the network sharing state of the specified type. This API uses an asynch ...@@ -674,7 +680,8 @@ Obtains the network sharing state of the specified type. This API uses an asynch
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI, (error, data) => { sharing.getSharingState(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
...@@ -719,7 +726,8 @@ Obtains the network sharing state of the specified type. This API uses a promise ...@@ -719,7 +726,8 @@ Obtains the network sharing state of the specified type. This API uses a promise
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI).then(data => { sharing.getSharingState(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
...@@ -760,7 +768,8 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch ...@@ -760,7 +768,8 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI, (error, data) => { sharing.getSharableRegexes(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
...@@ -805,7 +814,8 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise ...@@ -805,7 +814,8 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI).then(data => { sharing.getSharableRegexes(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
...@@ -842,7 +852,7 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb ...@@ -842,7 +852,7 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb
**Example** **Example**
```js ```js
sharing.on('sharingStateChange', (data) => { sharing.on('sharingStateChange', (data) => {
console.log('on sharingStateChange: ' + JSON.stringify(data)); console.log('on sharingStateChange: ' + JSON.stringify(data));
}); });
``` ```
...@@ -883,7 +893,8 @@ sharing.off('sharingStateChange', (data) => { ...@@ -883,7 +893,8 @@ sharing.off('sharingStateChange', (data) => {
## sharing.on('interfaceSharingStateChange') ## sharing.on('interfaceSharingStateChange')
on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state:
SharingIfaceState }>): void
Subscribes to network sharing state changes of a specified NIC. This API uses an asynchronous callback to return the result. Subscribes to network sharing state changes of a specified NIC. This API uses an asynchronous callback to return the result.
...@@ -910,14 +921,15 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an ...@@ -910,14 +921,15 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an
**Example** **Example**
```js ```js
sharing.on('interfaceSharingStateChange', (data) => { sharing.on('interfaceSharingStateChange', (data) => {
console.log('on interfaceSharingStateChange: ' + JSON.stringify(data)); console.log('on interfaceSharingStateChange:' + JSON.stringify(data));
}); });
``` ```
## sharing.off('interfaceSharingStateChange') ## sharing.off('interfaceSharingStateChange')
off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state:
SharingIfaceState }>): void
Unsubscribes from network sharing status changes of a specified NIC. This API uses an asynchronous callback to return the result. Unsubscribes from network sharing status changes of a specified NIC. This API uses an asynchronous callback to return the result.
...@@ -978,8 +990,8 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t ...@@ -978,8 +990,8 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t
**Example** **Example**
```js ```js
sharing.on('sharingUpstreamChange', (data) => { sharing.on('sharingUpstreamChange', (data) => {
console.log('on sharingUpstreamChange: ' + JSON.stringify(data)); console.log('on sharingUpstreamChange:' + JSON.stringify(data));
}); });
``` ```
......
...@@ -5,11 +5,12 @@ ...@@ -5,11 +5,12 @@
> 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. > 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.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event. You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server.
If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API.
When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event. If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event.
## Modules to Import ## Modules to Import
```js ```js
...@@ -21,9 +22,13 @@ import webSocket from '@ohos.net.webSocket'; ...@@ -21,9 +22,13 @@ import webSocket from '@ohos.net.webSocket';
```js ```js
import webSocket from '@ohos.net.webSocket'; import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://"; let defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => { ws.on('open', (err, value) => {
if (err != undefined) {
console.log(JSON.stringify(err))
return
}
console.log("on open, status:" + value['status'] + ", message:" + value['message']); console.log("on open, status:" + value['status'] + ", message:" + value['message']);
// When receiving the on('open') event, the client can use the send() API to communicate with the server. // When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => { ws.send("Hello, server!", (err, value) => {
...@@ -82,7 +87,6 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc ...@@ -82,7 +87,6 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
``` ```
## WebSocket ## WebSocket
Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object. Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object.
...@@ -93,6 +97,9 @@ connect(url: string, callback: AsyncCallback\<boolean\>): void ...@@ -93,6 +97,9 @@ connect(url: string, callback: AsyncCallback\<boolean\>): void
Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -125,13 +132,15 @@ ws.connect(url, (err, value) => { ...@@ -125,13 +132,15 @@ ws.connect(url, (err, value) => {
}); });
``` ```
### connect ### connect
connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -170,13 +179,15 @@ ws.connect(url, { ...@@ -170,13 +179,15 @@ ws.connect(url, {
}); });
``` ```
### connect ### connect
connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\> connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\>
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result. Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -214,7 +225,6 @@ promise.then((value) => { ...@@ -214,7 +225,6 @@ promise.then((value) => {
}); });
``` ```
### send ### send
send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
...@@ -255,7 +265,6 @@ ws.connect(url, (err, value) => { ...@@ -255,7 +265,6 @@ ws.connect(url, (err, value) => {
}); });
``` ```
### send ### send
send(data: string | ArrayBuffer): Promise\<boolean\> send(data: string | ArrayBuffer): Promise\<boolean\>
...@@ -300,7 +309,6 @@ ws.connect(url, (err, value) => { ...@@ -300,7 +309,6 @@ ws.connect(url, (err, value) => {
}); });
``` ```
### close ### close
close(callback: AsyncCallback\<boolean\>): void close(callback: AsyncCallback\<boolean\>): void
...@@ -328,7 +336,6 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return ...@@ -328,7 +336,6 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close((err, value) => { ws.close((err, value) => {
if (!err) { if (!err) {
console.log("close success") console.log("close success")
...@@ -338,7 +345,6 @@ ws.close((err, value) => { ...@@ -338,7 +345,6 @@ ws.close((err, value) => {
}); });
``` ```
### close ### close
close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
...@@ -367,7 +373,6 @@ Closes a WebSocket connection carrying specified options such as **code** and ** ...@@ -367,7 +373,6 @@ Closes a WebSocket connection carrying specified options such as **code** and **
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close({ ws.close({
code: 1000, code: 1000,
reason: "your reason" reason: "your reason"
...@@ -380,7 +385,6 @@ ws.close({ ...@@ -380,7 +385,6 @@ ws.close({
}); });
``` ```
### close ### close
close(options?: WebSocketCloseOptions): Promise\<boolean\> close(options?: WebSocketCloseOptions): Promise\<boolean\>
...@@ -414,7 +418,6 @@ Closes a WebSocket connection carrying specified options such as **code** and ** ...@@ -414,7 +418,6 @@ Closes a WebSocket connection carrying specified options such as **code** and **
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.close({ let promise = ws.close({
code: 1000, code: 1000,
reason: "your reason" reason: "your reason"
...@@ -426,7 +429,6 @@ promise.then((value) => { ...@@ -426,7 +429,6 @@ promise.then((value) => {
}); });
``` ```
### on('open') ### on('open')
on(type: 'open', callback: AsyncCallback\<Object\>): void on(type: 'open', callback: AsyncCallback\<Object\>): void
...@@ -442,7 +444,6 @@ Enables listening for the **open** events of a WebSocket connection. This API us ...@@ -442,7 +444,6 @@ Enables listening for the **open** events of a WebSocket connection. This API us
| type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.| | type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
...@@ -452,15 +453,14 @@ ws.on('open', (err, value) => { ...@@ -452,15 +453,14 @@ ws.on('open', (err, value) => {
}); });
``` ```
### off('open') ### off('open')
off(type: 'open', callback?: AsyncCallback\<Object\>): void off(type: 'open', callback?: AsyncCallback\<Object\>): void
Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **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. > 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 **System capability**: SystemCapability.Communication.NetStack
...@@ -483,15 +483,14 @@ ws.on('open', callback1); ...@@ -483,15 +483,14 @@ ws.on('open', callback1);
ws.off('open', callback1); ws.off('open', callback1);
``` ```
### on('message') ### on('message')
on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>**NOTE** > **NOTE**
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). > The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -511,16 +510,15 @@ ws.on('message', (err, value) => { ...@@ -511,16 +510,15 @@ ws.on('message', (err, value) => {
}); });
``` ```
### off('message') ### off('message')
off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void
Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>**NOTE** > **NOTE**
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). > The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
>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. > 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 **System capability**: SystemCapability.Communication.NetStack
...@@ -538,7 +536,6 @@ let ws = webSocket.createWebSocket(); ...@@ -538,7 +536,6 @@ let ws = webSocket.createWebSocket();
ws.off('message'); ws.off('message');
``` ```
### on('close') ### on('close')
on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void
...@@ -563,15 +560,14 @@ ws.on('close', (err, value) => { ...@@ -563,15 +560,14 @@ ws.on('close', (err, value) => {
}); });
``` ```
### off('close') ### off('close')
off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void
Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **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. > 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 **System capability**: SystemCapability.Communication.NetStack
...@@ -589,7 +585,6 @@ let ws = webSocket.createWebSocket(); ...@@ -589,7 +585,6 @@ let ws = webSocket.createWebSocket();
ws.off('close'); ws.off('close');
``` ```
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback): void on(type: 'error', callback: ErrorCallback): void
...@@ -603,7 +598,7 @@ Enables listening for the **error** events of a WebSocket connection. This API u ...@@ -603,7 +598,7 @@ Enables listening for the **error** events of a WebSocket connection. This API u
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------- | | -------- | ------------- | ---- | ------------------------------- |
| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.| | type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result.<br>Common error code: 200|
**Example** **Example**
...@@ -614,15 +609,14 @@ ws.on('error', (err) => { ...@@ -614,15 +609,14 @@ ws.on('error', (err) => {
}); });
``` ```
### off('error') ### off('error')
off(type: 'error', callback?: ErrorCallback): void off(type: 'error', callback?: ErrorCallback): void
Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **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. > 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 **System capability**: SystemCapability.Communication.NetStack
...@@ -640,7 +634,6 @@ let ws = webSocket.createWebSocket(); ...@@ -640,7 +634,6 @@ let ws = webSocket.createWebSocket();
ws.off('error'); ws.off('error');
``` ```
## WebSocketRequestOptions ## WebSocketRequestOptions
Defines the optional parameters carried in the request for establishing a WebSocket connection. Defines the optional parameters carried in the request for establishing a WebSocket connection.
...@@ -651,7 +644,6 @@ Defines the optional parameters carried in the request for establishing a WebSoc ...@@ -651,7 +644,6 @@ Defines the optional parameters carried in the request for establishing a WebSoc
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| header | Object | No | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.| | header | Object | No | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.|
## WebSocketCloseOptions ## WebSocketCloseOptions
Defines the optional parameters carried in the request for closing a WebSocket connection. Defines the optional parameters carried in the request for closing a WebSocket connection.
......
...@@ -120,3 +120,5 @@ ...@@ -120,3 +120,5 @@
- [Thermal Log Customization](subsys-thermal_log.md) - [Thermal Log Customization](subsys-thermal_log.md)
- [Thermal Policy Customization](subsys-thermal_policy.md) - [Thermal Policy Customization](subsys-thermal_policy.md)
- [Thermal Scene Customization](subsys-thermal_scene.md) - [Thermal Scene Customization](subsys-thermal_scene.md)
- Power Management
- [Power Mode Customization](subsys-power-mode-customization.md)
\ No newline at end of file
# Power Mode Customization
## Overview
### Introduction
By default, OpenHarmony provides the power mode feature, which offers the following options: normal mode, performance mode, power-saving mode, and ultra power-saving mode. However, the power mode configuration varies according to hardware specifications of different products. To address this issue, OpenHarmony provides the power mode customization function, allowing you to customize power modes depending on your hardware specifications.
### Basic Concepts
OpenHarmony supports the following four power modes, each of which corresponds to the specified power and performance policy.
- Normal mode: default power mode, in which the system brightness, screen-off time, and sleep time meet the requirements of most users.
- Performance mode: power mode that emphasizes on the performance, such as increasing the system brightness, disabling the screen-off time, and preventing the system from entering the sleep mode.
- Power-saving mode: power mode that emphasizes on power saving, such as decreasing the system brightness, reducing the screen-off time, and shortening the time for entering sleep mode.
- Ultra power-saving mode: power mode that emphasizes on ultimate power saving, such as greatly decreasing the system brightness, greatly reducing the screen-off time, and greatly shortening the time for entering sleep mode.
### Constraints
The configuration path for battery level customization is subject to the [configuration policy](https://gitee.com/openharmony/customization_config_policy). In this development guide, `/vendor` is used as an example of the configuration path. During actual development, you need to modify the customization path based on the product configuration policy.
## How to Develop
### Setting Up the Environment
**Hardware requirements:**
Development board running the standard system, for example, the DAYU200 or Hi3516D V300 open source suite.
**Environment requirements:**
For details about the requirements on the Linux environment, see [Quick Start](../quick-start/quickstart-overview.md).
### Getting Started with Development
The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568) as an example to illustrate power mode customization.
1. Create the `power_manager` folder in the product directory [vendor/hihope/rk3568](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568).
2. Create a target folder by referring to the [default power mode configuration folder](https://gitee.com/openharmony/powermgr_power_manager/tree/master/services/native/profile), and install it in `//vendor/hihope/rk3568/power_manager`. The content is as follows:
```text
profile
├── BUILD.gn
├── power_mode_config.xml
```
3. Write the custom `power_mode_config.xml` file by referring to the [power_mode_config.xml](https://gitee.com/openharmony/powermgr_power_manager/blob/master/services/native/profile/power_mode_config.xml) file in the default power mode configuration folder.
The **proxy** node is used to configure the power mode.
**Table 1** Description of the proxy node
| Power Mode| ID |
| :------ | --- |
| Normal mode| 600 |
| Power-saving mode| 601 |
| Performance mode| 602 |
| Ultra power-saving mode| 603 |
The **switch** node is used to configure items of the power mode.
**Table 2** Description of the **switch** node
| Configuration Item| ID | Value Range|
| :------ | ----- | ----- |
| Screen-off time| 101 | **value** indicates the screen-off duration, in unit of ms. It is an integer greater than or equal to **-1**. The value **-1** indicates that the screen-off function is disabled.|
| Auto sleep time| 102 | **value** indicates the time for automatically entering the sleep mode, in unit of ms. It is an integer greater than or equal to **-1**. The value **-1** indicates that the auto sleep function is disabled. |
| Automatic brightness adjustment| 103 | **value** indicates whether to enable automatic brightness adjustment. The options are as follows:<br>- **-1**: disable automatic brightness adjustment.<br>- **1**: enable automatic brightness adjustment.|
| Automatic screen rotation| 107 | **value** indicates whether to enable automatic screen rotation. The options are as follows:<br>- **-1**: disable automatic screen rotation.<br>- **1**: enable automatic screen rotation.|
| System brightness| 115 | **value** indicates the screen brightness. It is an integer ranging from 0 to 255.|
| Vibration switch| 120 | **value** indicates whether to enable vibration. The options are as follows:<br>- **-1**: disable vibration.<br>- **1**: enable vibration.|
The following uses the normal mode as an example:
```xml
<switch_proxy version="1">
<proxy id="600">
<switch id="101" value="10000"/>
<switch id="102" value="0"/>
<switch id="103" value="-1"/>
<switch id="107" value="1"/>
<switch id="115" value="30"/>
<switch id="120" value="1"/>
</proxy>
```
4. Write the `BUILD.gn` file by referring to the [BUILD.gn](https://gitee.com/openharmony/powermgr_power_manager/blob/master/services/native/profile/BUILD.gn) file in the default power mode configuration folder to pack the `power_mode_config.xml` file to the `/vendor/etc/power_config` directory. The configuration is as follows:
```shell
import("//base/powermgr/power_manager/powermgr.gni")
import("//build/ohos.gni")
## Install vendor power_mode_config.xml to /vendor/etc/power_config/power_mode_config.xml
ohos_prebuilt_etc("power_mode_config_vendor") { # custom name, for example, power_mode_config_vendor.
source = "power_mode_config.xml"
relative_install_dir = "power_config"
install_images = [ chipset_base_dir ] # Required configuration for installing the power_mode_config.xml file in the vendor directory, where chipset_base_dir = "vendor". If this field is left unspecified, the power_mode_config.xml file is installed in the system directory by default.
part_name = "${product_rk3568}" # Set part_name to product_rk3568 for subsequent build.
}
group("power_service_config") {
deps = [ ":power_mode_config_vendor" ]
}
```
5. Add the build target to `module_list` in [ohos.build](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/ohos.build) in the `/vendor/hihope/rk3568` directory. For example:
```json
{
"parts": {
"product_rk3568": {
"module_list": [
"//vendor/hihope/rk3568/default_app_config:default_app_config",
"//vendor/hihope/rk3568/image_conf:custom_image_conf",
"//vendor/hihope/rk3568/power_manager/profile:power_mode_config_vendor", # Add the configuration for building of power_mode_config_vendor.
"//vendor/hihope/rk3568/preinstall-config:preinstall-config",
"//vendor/hihope/rk3568/resourceschedule:resourceschedule",
"//vendor/hihope/rk3568/etc:product_etc_conf"
]
}
},
"subsystem": "product_hihope"
}
```
6. Build the customized version by referring to [Quick Start](../quick-start/quickstart-overview.md).
```shell
./build.sh --product-name rk3568 --ccache
```
7. Burn the customized version to the DAYU200 development board.
### Debugging and Verification
1. After startup, run the following command to launch the shell command line:
```shell
hdc shell
```
2. Set the power mode to the normal mode, and verify the setting.
1. Set the power mode to the normal mode.
```shell
power-shell setmode 600
```
2. Check whether the setting of the power mode is successful.
```shell
Set Mode: 600
Set Mode Success!
```
3. Obtain the auto sleep time.
```shell
hidumper -s 3301 -a -a
-------------------------------[ability]-------------------------------
----------------------------------PowerManagerService---------------------------------
POWER STATE DUMP:
Current State: INACTIVE Reason: 1 Time: 33227
ScreenOffTime: Timeout=10000ms
··· (Only the auto sleep time configuration is displayed here. Other information is omitted.)
```
4. Turn on the screen. If the screen turns off after 10 seconds, the setting of the auto sleep time is successful.
3. Set the power mode to the power-saving mode, and verify the setting.
1. Set the power mode to the power-saving mode.
```shell
power-shell setmode 601
```
2. Check whether the setting of the power mode is successful.
```shell
Set Mode: 601
Set Mode Success!
```
3. Obtain the auto sleep time.
```shell
hidumper -s 3301 -a -a
-------------------------------[ability]-------------------------------
----------------------------------PowerManagerService---------------------------------
POWER STATE DUMP:
Current State: INACTIVE Reason: 1 Time: 33227
ScreenOffTime: Timeout=20000ms
··· (Only the auto sleep time configuration is displayed here. Other information is omitted.)
```
4. Turn on the screen. If the screen turns off after 20 seconds, the setting of the auto sleep time is successful.
4. Set the power mode to the performance mode, and verify the setting.
1. Set the power mode to the performance mode.
```shell
power-shell setmode 602
```
2. Check whether the setting of the power mode is successful.
```shell
Set Mode: 602
Set Mode Success!
```
3. Obtain the auto sleep time.
```shell
hidumper -s 3301 -a -a
-------------------------------[ability]-------------------------------
----------------------------------PowerManagerService---------------------------------
POWER STATE DUMP:
Current State: INACTIVE Reason: 1 Time: 33227
ScreenOffTime: Timeout=30000ms
··· (Only the auto sleep time configuration is displayed here. Other information is omitted.)
```
4. Turn on the screen. If the screen turns off after 30 seconds, the setting of the auto sleep time is successful.
5. Set the power mode to the ultra power-saving mode, and verify the setting.
1. Set the power mode to the ultra power-saving mode.
```shell
power-shell setmode 603
```
2. Check whether the setting of the power mode is successful.
```shell
Set Mode: 603
Set Mode Success!
```
3. Obtain the auto sleep time.
```shell
hidumper -s 3301 -a -a
-------------------------------[ability]-------------------------------
----------------------------------PowerManagerService---------------------------------
POWER STATE DUMP:
Current State: INACTIVE Reason: 1 Time: 33227
ScreenOffTime: Timeout=40000ms
··· (Only the auto sleep time configuration is displayed here. Other information is omitted.)
```
4. Turn on the screen. If the screen turns off after 40 seconds, the setting of the auto sleep time is successful.
## Reference
During development, you can refer to the [default power mode configuration](https://gitee.com/openharmony/powermgr_power_manager/tree/master/services/native/profile):
[Default configuration](https://gitee.com/openharmony/powermgr_power_manager/blob/master/services/native/profile/power_mode_config.xml)
Packing path: `/system/etc/power_config/power_mode_config.xml`
...@@ -457,8 +457,8 @@ ...@@ -457,8 +457,8 @@
- [FaultLogger Development](subsystems/subsys-dfx-faultlogger.md) - [FaultLogger Development](subsystems/subsys-dfx-faultlogger.md)
- [Hiview Development](subsystems/subsys-dfx-hiview.md) - [Hiview Development](subsystems/subsys-dfx-hiview.md)
- Power - Power
- Power Consumption Statistics - Display Management
- [Power Consumption Statistics Customization](subsystems/subsys-power-stats-power-average-customization.md) - [System Brightness Customization](subsystems/subsys-power-brightness-customization.md)
- Battery Management - Battery Management
- [Battery Level and LED Color Mapping Customization](subsystems/subsys-power-level-LED-color.md) - [Battery Level and LED Color Mapping Customization](subsystems/subsys-power-level-LED-color.md)
- [Battery Temperature Protection Customization](subsystems/subsys-power-temperature-protection.md) - [Battery Temperature Protection Customization](subsystems/subsys-power-temperature-protection.md)
...@@ -466,6 +466,8 @@ ...@@ -466,6 +466,8 @@
- [Charging Current and Voltage Limit Customization](subsystems/subsys-power-charge-current-voltage-limit.md) - [Charging Current and Voltage Limit Customization](subsystems/subsys-power-charge-current-voltage-limit.md)
- [Charging Type Customization](subsystems/subsys-power-charge-type-customization.md) - [Charging Type Customization](subsystems/subsys-power-charge-type-customization.md)
- [Power-off Charging Animation Customization](subsystems/subsys-power-poweroff-charge-animation.md) - [Power-off Charging Animation Customization](subsystems/subsys-power-poweroff-charge-animation.md)
- Power Consumption Statistics
- [Power Consumption Statistics Customization](subsystems/subsys-power-stats-power-average-customization.md)
- Thermal Management - Thermal Management
- [Charging Idle State Customization](subsystems/subsys-thermal_charging_idle_state.md) - [Charging Idle State Customization](subsystems/subsys-thermal_charging_idle_state.md)
- [Thermal Control Customization](subsystems/subsys-thermal_control.md) - [Thermal Control Customization](subsystems/subsys-thermal_control.md)
...@@ -474,6 +476,8 @@ ...@@ -474,6 +476,8 @@
- [Thermal Log Customization](subsystems/subsys-thermal_log.md) - [Thermal Log Customization](subsystems/subsys-thermal_log.md)
- [Thermal Policy Customization](subsystems/subsys-thermal_policy.md) - [Thermal Policy Customization](subsystems/subsys-thermal_policy.md)
- [Thermal Scene Customization](subsystems/subsys-thermal_scene.md) - [Thermal Scene Customization](subsystems/subsys-thermal_scene.md)
- Power Management
- [Power Mode Customization](subsystems/subsys-power-mode-customization.md)
- Featured Topics - Featured Topics
- HPM Part - HPM Part
- [HPM Part Overview](hpm-part/hpm-part-about.md) - [HPM Part Overview](hpm-part/hpm-part-about.md)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册