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.
importconnectionfrom'@ohos.net.connection'
importconnectionfrom'@ohos.net.connection'
letnetCap={
letnetCap={
// 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.
// 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.
importconnectionfrom'@ohos.net.connection'
importconnectionfrom'@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.
importconnectionfrom'@ohos.net.connection'
importconnectionfrom'@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.
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.
importethernetfrom'@ohos.net.ethernet'
importethernetfrom'@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.
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.
importsharingfrom'@ohos.net.sharing'
importsharingfrom'@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.
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.
> **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).
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
@@ -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).
@@ -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
@@ -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).
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.
@@ -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));
| 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).
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.
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.
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.
| 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.|
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.
| 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.
| 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.
@@ -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.
letnetConnection=connection.createNetConnection()
letnetConnection=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.
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
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
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
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
> 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. |
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.
| 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
| 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.|
| 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.|
> 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';
// 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
letws=webSocket.createWebSocket();
letws=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.
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.
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.
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.
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).
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.
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.
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.
| 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.
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:
## 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:
··· (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):