提交 55be9b6b 编写于 作者: S shawn_he

update docs

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 b5f13e6c
......@@ -23,7 +23,7 @@ The following table provides only a simple description of the related APIs. For
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.|
## How to Develop
## How to Develop request APIs
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
......@@ -42,42 +42,42 @@ let httpRequest = http.createHttp();
// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements.
header: {
'Content-Type': 'application/json'
},
// This field is used to transfer data when the POST request is used.
extraData: {
"data": "data to send",
},
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => {
if (!err) {
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements.
header: {
'Content-Type': 'application/json'
},
// This field is used to transfer data when the POST request is used.
extraData: {
"data": "data to send",
},
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => {
if (!err) {
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
}
);
```
# Network Sharing
## 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.
> **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).
## Basic Concepts
- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot.
- Bluetooth sharing: Shares the network through Bluetooth.
- USB tethering: Shares the network using a USB flash drive.
- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot.
- Bluetooth sharing: Shares the network through Bluetooth.
- USB tethering: Shares the network using a USB flash drive.
## **Constraints**
- Programming language: C++ and JS
- 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.
- Programming language: C++ and JS
- 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.
## When to Use
Typical network sharing scenarios are as follows:
- Enabling network sharing
- Disabling network sharing
- Obtaining the data traffic of the shared network
- Enabling Network Sharing
- Disabling network sharing
- Obtaining the data traffic of the shared network
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md).
| Type| API| Description|
......@@ -54,18 +61,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
```
## Disabling network sharing
......@@ -79,18 +86,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call stopSharing to stop network sharing of the specified type.
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call stopSharing to stop network sharing of the specified type.
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
```
## 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
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
// Call getStatsTotalBytes to obtain the data traffic generated during data sharing.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// 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) => {
console.log(JSON.stringify(error));
});
// Call getStatsTotalBytes again. The data volume of network sharing has been cleared.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
// Call getStatsTotalBytes to obtain the data traffic generated during data sharing.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// 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) => {
console.log(JSON.stringify(error));
});
// Call getStatsTotalBytes again. The data volume of network sharing has been cleared.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
......@@ -13,10 +13,10 @@ The Socket Connection module allows an application to transmit data over a Socke
## When to Use
Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows:
Applications transmit data over TCP, UDP, or TLSSocket connections. The main application scenarios are as follows:
- Implementing data transmission over TCP/UDP Socket connections
- Implementing encrypted data transmission over TLS Socket connections
- Implementing data transmission over TCP/UDPSocket connections
- Implementing encrypted data transmission over TLSSocket connections
## Available APIs
......@@ -40,12 +40,12 @@ Socket connection functions are mainly implemented by the **socket** module. The
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDP Socket connection. |
| off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDP Socket connection. |
| on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCP Socket connection. |
| off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCP Socket connection.|
| on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDPSocket connection. |
| off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDPSocket connection. |
| on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCPSocket connection. |
| off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCPSocket connection.|
TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
TLSSocket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
| API| Description|
| -------- | -------- |
......@@ -56,28 +56,28 @@ TLS Socket connection functions are mainly provided by the **tls_socket** module
| getCertificate() | Obtains an object representing the local certificate.|
| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.|
| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.|
| getRemoteAddress() | Obtains the peer address of the TLS Socket connection.|
| getRemoteAddress() | Obtains the peer address of the TLSSocket connection.|
| getRemoteCertificate() | Obtains an object representing a peer certificate.|
| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.|
| getState() | Obtains the TLS Socket connection status.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLS Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLS Socket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLS Socket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the TLS Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the TLS Socket connection.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the TLS Socket connection.|
| getState() | Obtains the TLSSocket connection status.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLSSocket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLSSocket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLSSocket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the TLSSocket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the TLSSocket connection.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the TLSSocket connection.|
| send() | Sends data.|
| setExtraOptions() | Sets other properties of the TLS Socket connection.|
| setExtraOptions() | Sets other properties of the TLSSocket connection.|
## Transmitting Data over TCP/UDP Socket Connections
## Transmitting Data over TCP/UDPSocket Connections
The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example.
The implementation is similar for UDPSocket and TCPSocket connections. The following uses data transmission over a TCPSocket connection as an example.
1. Import the required **socket** module.
2. Create a **TCPSocket** object.
3. (Optional) Subscribe to TCP Socket connection events.
3. (Optional) Subscribe to TCPSocket connection events.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
......@@ -85,7 +85,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
6. Send data.
7. Enable the TCP Socket connection to be automatically closed after use.
7. Enable the TCPSocket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
......@@ -93,7 +93,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
// Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance();
// Subscribe to TCP Socket connection events.
// Subscribe to TCPSocket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
......@@ -152,7 +152,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
});
});
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
setTimeout(() => {
tcp.close((err) => {
console.log('close socket.')
......@@ -163,11 +163,11 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
}, 30 * 1000);
```
## Implementing Encrypted Data Transmission over TLS Socket Connections
## Implementing encrypted data transmission over TLSSocket connections
### How to Develop
TLS Socket connection process on the client:
TLSSocket connection process on the client:
1. Import the required **socket** module.
......@@ -177,145 +177,143 @@ TLS Socket connection process on the client:
4. Create a **TLSSocket** object.
5. (Optional) Subscribe to TLS Socket connection events.
5. (Optional) Subscribe to TLSSocket connection events.
6. Send data.
7. Enable the TLS Socket connection to be automatically closed after use.
7. Enable the TLSSocket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events.
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tlsTwoWay.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
// Set up a connection to the specified IP address and port number.
address: {
address: "192.168.xx.xxx",
port: xxxx, // Port
family: 1,
},
// Set the parameters used for authentication during communication.
secureOptions: {
key: "xxxx", // Key
cert: "xxxx", // Digital certificate
ca: ["xxxx"], // CA certificate
passwd: "xxxx", // Password for generating the key
protocols: [socket.Protocol.TLSv12], // Communication protocol
useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
// Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events.
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tlsTwoWay.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"], // CA certificate
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
// Create a TLSSocket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLSSocket connection events.
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tlsTwoWay.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
// Set up a connection to the specified IP address and port number.
address: {
address: "192.168.xx.xxx",
port: xxxx, // Port
family: 1,
},
// Set the parameters used for authentication during communication.
secureOptions: {
key: "xxxx", // Key
cert: "xxxx", // Digital certificate
ca: ["xxxx"], // CA certificate
passwd: "xxxx", // Password for generating the key
protocols: [socket.Protocol.TLSv12], // Communication protocol
useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
// Create a TLSSocket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLSSocket connection events.
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tlsTwoWay.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"], // CA certificate
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
```
# 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.
## 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.
| API | Description |
| API| Description|
| -------- | -------- |
| createWebSocket() | Creates a WebSocket connection. |
| connect() | Establishes a WebSocket connection to a given URL. |
| send() | Sends data through the WebSocket connection. |
| close() | Closes 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. |
| on(type: 'message') | Enables 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. |
| off(type: 'close') | Disables listening for **close** 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. |
| createWebSocket() | Creates a WebSocket connection.|
| connect() | Establishes a WebSocket connection to a given URL.|
| send() | Sends data through the WebSocket connection.|
| close() | Closes 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.|
| on(type: 'message') | Enables 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.|
| off(type: 'close') | Disables listening for **close** 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.|
## How to Develop
1. Import the required WebSocket module.
1. Import the required webSocket module.
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.
5. Close the WebSocket connection if it is no longer needed.
```js
import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
console.log("on open, status:" + JSON.stringify(value));
// When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("Message sent successfully");
} else {
console.log("Failed to send the message. Err:" + JSON.stringify(err));
}
});
});
ws.on('message', (err, value) => {
console.log("on message, message:" + value);
// When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
if (value === 'bye') {
ws.close((err, value) => {
if (!err) {
console.log("Connection closed successfully");
} else {
console.log("Failed to close the connection. Err: " + JSON.stringify(err));
}
});
}
});
ws.on('close', (err, value) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err));
});
ws.connect(defaultIpAddress, (err, value) => {
if (!err) {
console.log("Connected successfully");
} else {
console.log("Connection failed. Err:" + JSON.stringify(err));
}
});
```
```js
import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
console.log("on open, status:" + JSON.stringify(value));
// When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("Message sent successfully");
} else {
console.log("Failed to send the message. Err:" + JSON.stringify(err));
}
});
});
ws.on('message', (err, value) => {
console.log("on message, message:" + value);
// When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
if (value === 'bye') {
ws.close((err, value) => {
if (!err) {
console.log("Connection closed successfully");
} else {
console.log("Failed to close the connection. Err: " + JSON.stringify(err));
}
});
}
});
ws.on('close', (err, value) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err));
});
ws.connect(defaultIpAddress, (err, value) => {
if (!err) {
console.log("Connected successfully");
} else {
console.log("Connection failed. Err:" + JSON.stringify(err));
}
});
```
......@@ -199,8 +199,8 @@ The development process consists of the following main steps:
2. Run the CMake tool.
- Use hdc_std to connect to the RK3568 development board and put **demo** and **mobilenetv2.ms** to the same directory on the board.
- Run the hdc_std shell command to access the development board, go to the directory where **demo** is located, and run the following command:
- Use hdc_std to connect to the device and put **demo** and **mobilenetv2.ms** to the same directory on the board.
- Run the hdc_std shell command to access the device, go to the directory where **demo** is located, and run the following command:
```shell
./demo mobilenetv2.ms
......
# Geolocation
# @ohos.geolocation (Geolocation)
The **geolocation** module provides a wide array of location services, including GNSS positioning, network positioning, geocoding, reverse geocoding, and geofencing.
......
# @ohos.hidebug (HiDebug)
The **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data.
> **NOTE**<br>
> **NOTE**
>
> 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 **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data.
## Modules to Import
......@@ -19,13 +19,11 @@ getNativeHeapSize(): bigint
Obtains the total heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
| Type | Description |
| Type | Description |
| ------ | --------------------------- |
| bigint | Total heap memory size of the application, in KB.|
......@@ -42,8 +40,6 @@ getNativeHeapAllocatedSize(): bigint
Obtains the allocated heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
......@@ -65,8 +61,6 @@ getNativeHeapFreeSize(): bigint
Obtains the free heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
......@@ -163,76 +157,6 @@ For example, if the CPU usage is **50%**, **0.5** is returned.
let cpuUsage = hidebug.getCpuUsage();
```
## hidebug.startProfiling<sup>(deprecated)</sup>
startProfiling(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9) instead.
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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.stopProfiling<sup>(deprecated)</sup>
stopProfiling() : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9) instead.
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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.dumpHeapData<sup>(deprecated)</sup>
dumpHeapData(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9) instead.
Exports the heap data.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.dumpHeapData("heap-20220216");
```
## hidebug.getServiceDump<sup>9+<sup>
getServiceDump(serviceid : number, fd : number, args : Array\<string>) : void
......@@ -251,11 +175,10 @@ Obtains system service information.
| fd | number | Yes | File descriptor to which data is written by the API.|
| args | Array\<string> | Yes | Parameter list corresponding to the **Dump** API of the system service.|
**Example**
```js
import fileio from '@ohos.fileio'
import fs from '@ohos.file.fs'
import hidebug from '@ohos.hidebug'
import featureAbility from '@ohos.ability.featureAbility'
......@@ -263,7 +186,7 @@ let context = featureAbility.getContext();
context.getFilesDir().then((data) => {
var path = data + "/serviceInfo.txt"
console.info("output path: " + path)
let fd = fileio.openSync(path, 0o102, 0o666)
let fd = fs.openSync(path, 0o102, 0o666)
var serviceId = 10
var args = new Array("allInfo")
try {
......@@ -272,7 +195,7 @@ context.getFilesDir().then((data) => {
console.info(error.code)
console.info(error.message)
}
fileio.closeSync(fd);
fs.closeSync(fd);
})
```
......@@ -360,3 +283,79 @@ try {
console.info(error.message)
}
```
## hidebug.startProfiling<sup>(deprecated)</sup>
startProfiling(filename : string) : void
> **NOTE**
>
> 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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.stopProfiling<sup>(deprecated)</sup>
stopProfiling() : void
> **NOTE**
>
> 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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.dumpHeapData<sup>(deprecated)</sup>
dumpHeapData(filename : string) : void
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9).
Exports the heap data.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.dumpHeapData("heap-20220216");
```
......@@ -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**.
>**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.
>
......@@ -24,43 +24,43 @@ let httpRequest = http.createHttp();
// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements.
header: {
'Content-Type': 'application/json'
},
// This field is used to transfer data when the POST request is used.
extraData: {
"data": "data to send",
},
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => {
if (!err) {
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements.
header: {
'Content-Type': 'application/json'
},
// This parameter is used to transfer data when the POST request is used.
extraData: {
"data": "data to send",
},
expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => {
if (!err) {
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
}
);
```
......@@ -82,6 +82,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req
```js
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```
......@@ -95,8 +96,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.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
> **NOTE**
> This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
......@@ -121,7 +122,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
| 2300052 | Server returned nothing (no headers, no data). |
| 2300999 | Unknown Other Error. |
>**NOTE**
> **NOTE**
> 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).
......@@ -129,14 +130,14 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
```js
httpRequest.request("EXAMPLE_URL", (err, data) => {
if (!err) {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
}
if (!err) {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
}
});
```
......@@ -146,8 +147,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.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
> **NOTE**
> This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
......@@ -197,7 +198,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**NOTE**
> **NOTE**
> 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).
......@@ -205,25 +206,25 @@ Initiates an HTTP request containing specified options to a given URL. This API
```js
httpRequest.request("EXAMPLE_URL",
{
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
'Content-Type': 'application/json'
},
readTimeout: 60000,
connectTimeout: 60000
}, (err, data) => {
}, (err, data) => {
if (!err) {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
console.info('header.Content-Type:' + data.header['Content-Type']);
console.info('header.Status-Line:' + data.header['Status-Line']);
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
console.info('header.Content-Type:' + data.header['Content-Type']);
console.info('header.Status-Line:' + data.header['Status-Line']);
} else {
console.info('error:' + JSON.stringify(err));
console.info('error:' + JSON.stringify(err));
}
});
});
```
### request
......@@ -232,8 +233,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.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
> **NOTE**
> This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
......@@ -288,7 +289,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**NOTE**
> **NOTE**
> 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).
......@@ -296,22 +297,22 @@ Initiates an HTTP request containing specified options to a given URL. This API
```js
let promise = httpRequest.request("EXAMPLE_URL", {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
});
promise.then((data) => {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
console.info('header.Content-Type:' + data.header['Content-Type']);
console.info('header.Status-Line:' + data.header['Status-Line']);
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
console.info('header.Content-Type:' + data.header['Content-Type']);
console.info('header.Status-Line:' + data.header['Status-Line']);
}).catch((err) => {
console.info('error:' + JSON.stringify(err));
console.info('error:' + JSON.stringify(err));
});
```
......@@ -335,8 +336,8 @@ on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void
Registers an observer for HTTP Response Header events.
>**NOTE**
>This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8).
> **NOTE**
> This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8).
**System capability**: SystemCapability.Communication.NetStack
......@@ -351,7 +352,7 @@ Registers an observer for HTTP Response Header events.
```js
httpRequest.on('headerReceive', (data) => {
console.info('error:' + JSON.stringify(data));
console.info('error:' + JSON.stringify(data));
});
```
......@@ -361,7 +362,7 @@ off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void
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).
>
......@@ -401,7 +402,7 @@ Registers an observer for HTTP Response Header events.
```js
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
console.info('header: ' + JSON.stringify(header));
});
```
......@@ -411,8 +412,8 @@ off(type: 'headersReceive', callback?: Callback\<Object\>): void
Unregisters the observer for HTTP Response Header events.
>**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.
> **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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -448,7 +449,7 @@ Registers a one-time observer for HTTP Response Header events. Once triggered, t
```js
httpRequest.once('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
console.info('header: ' + JSON.stringify(header));
});
```
......@@ -460,11 +461,11 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. |
| 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> |
| 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.|
| method | [RequestMethod](#requestmethod) | No | Request method. The default value is **GET**. |
| 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 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**. |
| 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'}**. |
| 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. |
......@@ -539,10 +540,10 @@ Defines the response to an HTTP request.
| 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|
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. |
| 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. |
| 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. |
## http.createHttpResponseCache<sup>9+</sup>
......@@ -569,6 +570,7 @@ Creates a default object to store responses to HTTP access requests.
```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
```
......@@ -651,6 +653,7 @@ httpResponseCache.delete(err => {
console.info('delete success');
});
```
### delete<sup>9+</sup>
delete(): Promise\<void\>
......
......@@ -48,19 +48,19 @@ Sets the network interface configuration. This API uses an asynchronous callback
```js
ethernet.setIfaceConfig("eth0", {
mode: 0,
ipAddr: "192.168.xx.xxx",
route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx",
netMask: "255.255.255.0",
dnsServers: "1.1.1.1",
domain: "2.2.2.2"
mode: 0,
ipAddr: "192.168.xx.xxx",
route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx",
netMask: "255.255.255.0",
dnsServers: "1.1.1.1",
domain: "2.2.2.2"
}, (error) => {
if (error) {
console.log("setIfaceConfig callback error = " + JSON.stringify(error));
} else {
console.log("setIfaceConfig callback ok ");
}
if (error) {
console.log("setIfaceConfig callback error = " + JSON.stringify(error));
} else {
console.log("setIfaceConfig callback ok ");
}
});
```
......@@ -106,17 +106,17 @@ Sets the network interface configuration. This API uses a promise to return the
```js
ethernet.setIfaceConfig("eth0", {
mode: 0,
ipAddr: "192.168.xx.xxx",
route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx",
netMask: "255.255.255.0",
dnsServers: "1.1.1.1",
domain: "2.2.2.2"
mode: 0,
ipAddr: "192.168.xx.xxx",
route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx",
netMask: "255.255.255.0",
dnsServers: "1.1.1.1",
domain: "2.2.2.2"
}).then(() => {
console.log("setIfaceConfig promise ok ");
console.log("setIfaceConfig promise ok ");
}).catch(error => {
console.log("setIfaceConfig promise error = " + JSON.stringify(error));
console.log("setIfaceConfig promise error = " + JSON.stringify(error));
});
```
......@@ -154,17 +154,17 @@ Obtains the configuration of a network interface. This API uses an asynchronous
```js
ethernet.getIfaceConfig("eth0", (error, value) => {
if (error) {
console.log("getIfaceConfig callback error = " + JSON.stringify(error));
} else {
console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode));
console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr));
console.log("getIfaceConfig callback route = " + JSON.stringify(value.route));
console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway));
console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask));
console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers));
console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain));
}
if (error) {
console.log("getIfaceConfig callback error = " + JSON.stringify(error));
} else {
console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode));
console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr));
console.log("getIfaceConfig callback route = " + JSON.stringify(value.route));
console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway));
console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask));
console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers));
console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain));
}
});
```
......@@ -207,15 +207,15 @@ Obtains the configuration of a network interface. This API uses a promise to ret
```js
ethernet.getIfaceConfig("eth0").then((data) => {
console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promise route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain));
console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promise route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain));
}).catch(error => {
console.log("getIfaceConfig promise error = " + JSON.stringify(error));
console.log("getIfaceConfig promise error = " + JSON.stringify(error));
});
```
......@@ -253,11 +253,11 @@ Checks whether a network interface is active. This API uses an asynchronous call
```js
ethernet.isIfaceActive("eth0", (error, value) => {
if (error) {
console.log("whether2Activate callback error = " + JSON.stringify(error));
} else {
console.log("whether2Activate callback = " + JSON.stringify(value));
}
if (error) {
console.log("whether2Activate callback error = " + JSON.stringify(error));
} else {
console.log("whether2Activate callback = " + JSON.stringify(value));
}
});
```
......@@ -300,9 +300,9 @@ Checks whether a network interface is active. This API uses a promise to return
```js
ethernet.isIfaceActive("eth0").then((data) => {
console.log("isIfaceActive promise = " + JSON.stringify(data));
console.log("isIfaceActive promise = " + JSON.stringify(data));
}).catch(error => {
console.log("isIfaceActive promise error = " + JSON.stringify(error));
console.log("isIfaceActive promise error = " + JSON.stringify(error));
});
```
......@@ -336,14 +336,14 @@ Obtains the list of all active network interfaces. This API uses an asynchronous
```js
ethernet.getAllActiveIfaces((error, value) => {
if (error) {
console.log("getAllActiveIfaces callback error = " + JSON.stringify(error));
} else {
console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length));
for (let i = 0; i < value.length; i++) {
console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i]));
}
if (error) {
console.log("getAllActiveIfaces callback error = " + JSON.stringify(error));
} else {
console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length));
for (let i = 0; i < value.length; i++) {
console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i]));
}
}
});
```
......@@ -377,15 +377,83 @@ Obtains the list of all active network interfaces. This API uses a promise to re
```js
ethernet.getAllActiveIfaces().then((data) => {
console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length));
for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i]));
}
console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length));
for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i]));
}
}).catch(error => {
console.log("getAllActiveIfaces promise error = " + JSON.stringify(error));
console.log("getAllActiveIfaces promise error = " + JSON.stringify(error));
});
```
## 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
Defines the network configuration for the Ethernet connection.
......
......@@ -43,10 +43,12 @@ Sets a background network policy. This API uses an asynchronous callback to retu
```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => {
this.callBack(error, data);
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
this.callBack(error, data);
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
}
)
;
```
## policy.setBackgroundPolicy
......@@ -84,9 +86,9 @@ Sets a background network policy. This API uses a promise to return the result.
**Example**
```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -118,9 +120,9 @@ Obtains the background network policy. This API uses an asynchronous callback to
```js
policy.isBackgroundAllowed((error, data) => {
this.callBack(error, data);
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
this.callBack(error, data);
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
......@@ -151,9 +153,9 @@ Obtains the background network policy. This API uses a promise to return the res
**Example**
```js
policy.isBackgroundAllowed().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.isBackgroundAllowed().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -190,10 +192,10 @@ Sets an application-specific network policy. This API uses an asynchronous callb
```js
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), (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -234,11 +236,11 @@ Sets an application-specific network policy. This API uses a promise to return t
```js
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) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -274,7 +276,7 @@ Obtains an application-specific network policy by **uid**. This API uses an asyn
```js
policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -313,9 +315,9 @@ Obtains an application-specific network policy by **uid**. This API uses a promi
**Example**
```js
policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -351,7 +353,7 @@ Obtains the UID array of applications configured with a certain application-spec
```js
policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -390,9 +392,9 @@ Obtains the UID array of applications configured with a certain application-spec
**Example**
```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -425,7 +427,7 @@ Obtains the network quota policies. This API uses an asynchronous callback to re
```js
policy.getNetQuotaPolicies((error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -456,9 +458,9 @@ Obtains the network quota policies. This API uses a promise to return the result
**Example**
```js
policy.getNetQuotaPolicies().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.getNetQuotaPolicies().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -493,12 +495,22 @@ Sets an array of network quota policies. This API uses an asynchronous callback
**Example**
```js
let param = {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};
let param = {
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);
policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -537,13 +549,23 @@ Sets an array of network quota policies. This API uses a promise to return the r
**Example**
```js
let param = {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};
let param = {
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);
policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -579,7 +601,7 @@ Restores all the policies (cellular network, background network, firewall, and a
```js
this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam, (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -619,9 +641,9 @@ Restores all the policies (cellular network, background network, firewall, and a
```js
this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam).then(function(error, data){
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.restoreAllPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -659,10 +681,10 @@ Checks whether an application is allowed to access metered networks. This API us
```js
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)), (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -704,11 +726,11 @@ Checks whether an application is allowed to access metered networks. This API us
```js
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) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(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(data))
})
```
......@@ -746,10 +768,10 @@ Checks whether an application is allowed to access the given network. This API u
```js
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, (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -790,11 +812,11 @@ Checks whether an application is allowed to access the given network. This API u
```js
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) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -831,10 +853,10 @@ Sets whether to add an application to the device idle allowlist. This API uses a
```js
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)), (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -875,11 +897,11 @@ Sets whether to add an application to the device idle allowlist. This API uses a
```js
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) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(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(data))
})
```
......@@ -912,7 +934,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
```js
policy.getDeviceIdleAllowList((error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -943,9 +965,9 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
**Example**
```js
policy.getDeviceIdleAllowList().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.getDeviceIdleAllowList().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -981,7 +1003,7 @@ Obtains the background network policies configured for the given application. Th
```js
this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -1021,9 +1043,9 @@ Obtains the background network policies configured for the given application. Th
```js
this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -1059,7 +1081,7 @@ Restores all the policies (cellular network, background network, firewall, and a
```js
this.firstParam = iccid
policy.resetPolicies(this.firstParam, (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -1098,13 +1120,13 @@ Restores all the policies (cellular network, background network, firewall, and a
**Example**
```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) {
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
})
this.firstParam = iccid
policy.resetPolicies(this.firstParam).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.resetPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -1142,10 +1164,10 @@ Updates a reminder policy. This API uses an asynchronous callback to return the
```js
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), (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -1187,11 +1209,11 @@ Updates a reminder policy. This API uses a promise to return the result.
```js
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) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(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(data))
})
```
......@@ -1228,10 +1250,10 @@ Sets whether to add an application to the power-saving allowlist. This API uses
```js
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)), (error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -1272,11 +1294,11 @@ Sets whether to add an application to the power-saving allowlist. This API uses
```js
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) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(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(data))
})
```
......@@ -1309,7 +1331,7 @@ Obtains the UID array of applications that are on the power-saving allowlist. Th
```js
policy.getPowerSaveAllowList((error, data) => {
this.callBack(error, data);
this.callBack(error, data);
});
```
......@@ -1340,9 +1362,9 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
**Example**
```js
policy.getPowerSaveAllowList().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
policy.getPowerSaveAllowList().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
......@@ -1371,7 +1393,7 @@ Subscribes to policy changes. This API uses an asynchronous callback to return t
```js
policy.on('netUidPolicyChange', (data) => {
this.log('on netUidPolicyChange: ' + JSON.stringify(data));
this.log('on netUidPolicyChange: ' + JSON.stringify(data));
})
```
......@@ -1396,7 +1418,7 @@ Subscribes to rule changes. This API uses an asynchronous callback to return the
```js
policy.on('netUidRuleChange', (data) => {
this.log('on netUidRuleChange: ' + JSON.stringify(data));
this.log('on netUidRuleChange: ' + JSON.stringify(data));
})
```
......@@ -1421,7 +1443,7 @@ Subscribes to metered **iface** changes. This API uses an asynchronous callback
```js
policy.on('netMeteredIfacesChange', (data) => {
this.log('on netMeteredIfacesChange: ' + JSON.stringify(data));
this.log('on netMeteredIfacesChange: ' + JSON.stringify(data));
})
```
......@@ -1446,7 +1468,7 @@ Subscribes to network quota policy changes. This API uses an asynchronous callba
```js
policy.on('netQuotaPolicyChange', (data) => {
this.log('on netQuotaPolicyChange: ' + JSON.stringify(data));
this.log('on netQuotaPolicyChange: ' + JSON.stringify(data));
})
```
......@@ -1471,7 +1493,7 @@ Subscribes to background network policy changes. This API uses an asynchronous c
```js
policy.on('netBackgroundPolicyChange', (data) => {
this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data));
this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data));
})
```
......
......@@ -43,8 +43,8 @@ Checks whether network sharing is supported. This API uses an asynchronous callb
```js
sharing.isSharingSupported((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
......@@ -79,9 +79,9 @@ Checks whether network sharing is supported. This API uses a promise to return t
```js
sharing.isSharingSupported().then(data => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(error));
});
```
......@@ -115,8 +115,8 @@ Checks whether network sharing is in progress. This API uses an asynchronous cal
```js
sharing.isSharing((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
......@@ -150,9 +150,9 @@ Checks whether network sharing is in progress. This API uses a promise to return
```js
sharing.isSharing().then(data => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(error));
});
```
......@@ -194,9 +194,10 @@ Starts network sharing of a specified type. This API uses an asynchronous callba
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(error));
});
```
......@@ -243,11 +244,12 @@ Starts network sharing of a specified type. This API uses a promise to return th
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI).then(() => {
console.log("start wifi sharing successful");
console.log("start wifi sharing successful");
}).catch(error => {
console.log("start wifi sharing failed");
console.log("start wifi sharing failed");
});
```
......@@ -287,9 +289,10 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(error));
});
```
......@@ -334,11 +337,12 @@ Stops network sharing of a specified type. This API uses a promise to return the
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI).then(() => {
console.log("stop wifi sharing successful");
console.log("stop wifi sharing successful");
}).catch(error => {
console.log("stop wifi sharing failed");
console.log("stop wifi sharing failed");
});
```
......@@ -372,8 +376,8 @@ Obtains the volume of mobile data traffic received via network sharing. This API
```js
sharing.getStatsRxBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
......@@ -407,9 +411,9 @@ Obtains the volume of mobile data traffic received via network sharing. This API
```js
sharing.getStatsRxBytes().then(data => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(error));
});
```
......@@ -443,8 +447,8 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use
```js
sharing.getStatsTxBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
......@@ -478,9 +482,9 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use
```js
sharing.getStatsTxBytes().then(data => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(error));
});
```
......@@ -514,8 +518,8 @@ Obtains the volume of mobile data traffic sent and received via network sharing.
```js
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
......@@ -549,9 +553,9 @@ Obtains the volume of mobile data traffic sent and received via network sharing.
```js
sharing.getStatsTotalBytes().then(data => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(error));
});
```
......@@ -588,10 +592,11 @@ Obtains the names of NICs in the specified network sharing state. This API uses
```js
import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
......@@ -633,11 +638,12 @@ Obtains the names of NICs in the specified network sharing state. This API uses
```js
import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(error));
});
```
......@@ -674,10 +680,11 @@ Obtains the network sharing state of the specified type. This API uses an asynch
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
......@@ -719,11 +726,12 @@ Obtains the network sharing state of the specified type. This API uses a promise
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(error));
});
```
......@@ -760,10 +768,11 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
......@@ -805,11 +814,12 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(error));
});
```
......@@ -842,8 +852,8 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb
**Example**
```js
sharing.on('sharingStateChange', (data) => {
console.log('on sharingStateChange: ' + JSON.stringify(data));
sharing.on('sharingStateChange', (data) => {
console.log('on sharingStateChange: ' + JSON.stringify(data));
});
```
......@@ -877,7 +887,7 @@ Unsubscribes from network sharing state changes. This API uses an asynchronous c
```js
sharing.off('sharingStateChange', (data) => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
});
```
......@@ -910,8 +920,8 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an
**Example**
```js
sharing.on('interfaceSharingStateChange', (data) => {
console.log('on interfaceSharingStateChange: ' + JSON.stringify(data));
sharing.on('interfaceSharingStateChange', (data) => {
console.log('on interfaceSharingStateChange:' + JSON.stringify(data));
});
```
......@@ -945,7 +955,7 @@ Unsubscribes from network sharing status changes of a specified NIC. This API us
```js
sharing.off('interfaceSharingStateChange', (data) => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
});
```
......@@ -978,8 +988,8 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t
**Example**
```js
sharing.on('sharingUpstreamChange', (data) => {
console.log('on sharingUpstreamChange: ' + JSON.stringify(data));
sharing.on('sharingUpstreamChange', (data) => {
console.log('on sharingUpstreamChange:' + JSON.stringify(data));
});
```
......@@ -1013,7 +1023,7 @@ Unsubscribes from upstream network changes. This API uses an asynchronous callba
```js
sharing.off('sharingUpstreamChange', (data) => {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data));
});
```
......
# UI Appearance
# @ohos.uiAppearance (UI Appearance)
The **uiAppearance** module provides basic capabilities for managing the system appearance. It allows for color mode configuration currently, and will introduce more features over time.
......
......@@ -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.
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.
## Modules to Import
```js
......@@ -21,44 +22,48 @@ import webSocket from '@ohos.net.webSocket';
```js
import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://";
let defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
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.
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err));
}
});
if (err != undefined) {
console.log(JSON.stringify(err))
return
}
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.
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err));
}
});
});
ws.on('message', (err, value) => {
console.log("on message, message:" + value);
// When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
if (value === 'bye') {
ws.close((err, value) => {
if (!err) {
console.log("close success");
} else {
console.log("close fail, err is " + JSON.stringify(err));
}
});
}
console.log("on message, message:" + value);
// When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
if (value === 'bye') {
ws.close((err, value) => {
if (!err) {
console.log("close success");
} else {
console.log("close fail, err is " + JSON.stringify(err));
}
});
}
});
ws.on('close', (err, value) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason);
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err));
console.log("on error, error:" + JSON.stringify(err));
});
ws.connect(defaultIpAddress, (err, value) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err));
}
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err));
}
});
```
......@@ -82,7 +87,6 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc
let ws = webSocket.createWebSocket();
```
## WebSocket
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
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
**System capability**: SystemCapability.Communication.NetStack
......@@ -117,21 +124,23 @@ Initiates a WebSocket request to establish a WebSocket connection to a given URL
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, (err, value) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err))
}
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err))
}
});
```
### connect
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.
> **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
**System capability**: SystemCapability.Communication.NetStack
......@@ -157,26 +166,28 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, {
header: {
"key": "value",
"key2": "value2"
}
header: {
"key": "value",
"key2": "value2"
}
}, (err, value) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err))
}
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err))
}
});
```
### connect
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.
> **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
**System capability**: SystemCapability.Communication.NetStack
......@@ -208,13 +219,12 @@ let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.connect(url);
promise.then((value) => {
console.log("connect success")
console.log("connect success")
}).catch((err) => {
console.log("connect fail, error:" + JSON.stringify(err))
console.log("connect fail, error:" + JSON.stringify(err))
});
```
### send
send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
......@@ -245,17 +255,16 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, (err, value) => {
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err))
}
});
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err))
}
});
});
```
### send
send(data: string | ArrayBuffer): Promise\<boolean\>
......@@ -291,16 +300,15 @@ Sends data through a WebSocket connection. This API uses a promise to return the
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, (err, value) => {
let promise = ws.send("Hello, server!");
promise.then((value) => {
console.log("send success")
}).catch((err) => {
console.log("send fail, error:" + JSON.stringify(err))
});
let promise = ws.send("Hello, server!");
promise.then((value) => {
console.log("send success")
}).catch((err) => {
console.log("send fail, error:" + JSON.stringify(err))
});
});
```
### close
close(callback: AsyncCallback\<boolean\>): void
......@@ -328,17 +336,15 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return
```js
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close((err, value) => {
if (!err) {
console.log("close success")
} else {
console.log("close fail, err is " + JSON.stringify(err))
}
if (!err) {
console.log("close success")
} else {
console.log("close fail, err is " + JSON.stringify(err))
}
});
```
### close
close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
......@@ -367,20 +373,18 @@ Closes a WebSocket connection carrying specified options such as **code** and **
```js
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close({
code: 1000,
reason: "your reason"
code: 1000,
reason: "your reason"
}, (err, value) => {
if (!err) {
console.log("close success")
} else {
console.log("close fail, err is " + JSON.stringify(err))
}
if (!err) {
console.log("close success")
} else {
console.log("close fail, err is " + JSON.stringify(err))
}
});
```
### close
close(options?: WebSocketCloseOptions): Promise\<boolean\>
......@@ -414,19 +418,17 @@ Closes a WebSocket connection carrying specified options such as **code** and **
```js
let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.close({
code: 1000,
reason: "your reason"
code: 1000,
reason: "your reason"
});
promise.then((value) => {
console.log("close success")
console.log("close success")
}).catch((err) => {
console.log("close fail, err is " + JSON.stringify(err))
console.log("close fail, err is " + JSON.stringify(err))
});
```
### on('open')
on(type: 'open', callback: AsyncCallback\<Object\>): void
......@@ -442,25 +444,23 @@ 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.|
| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. |
**Example**
```js
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
console.log("on open, status:" + value['status'] + ", message:" + value['message']);
console.log("on open, status:" + value['status'] + ", message:" + value['message']);
});
```
### off('open')
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.
>**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.
> **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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -476,22 +476,21 @@ Disables listening for the **open** events of a WebSocket connection. This API u
```js
let ws = webSocket.createWebSocket();
let callback1 = (err, value) => {
console.log("on open, status:" + value['status'] + ", message:" + value['message']);
console.log("on open, status:" + value['status'] + ", message:" + value['message']);
}
ws.on('open', callback1);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
ws.off('open', callback1);
```
### on('message')
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.
>**NOTE**
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
> **NOTE**
> The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
**System capability**: SystemCapability.Communication.NetStack
......@@ -507,20 +506,19 @@ Enables listening for the **message** events of a WebSocket connection. This API
```js
let ws = webSocket.createWebSocket();
ws.on('message', (err, value) => {
console.log("on message, message:" + value);
console.log("on message, message:" + value);
});
```
### off('message')
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.
>**NOTE**
>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.
> **NOTE**
> 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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -538,7 +536,6 @@ let ws = webSocket.createWebSocket();
ws.off('message');
```
### on('close')
on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void
......@@ -559,19 +556,18 @@ Enables listening for the **close** events of a WebSocket connection. This API u
```js
let ws = webSocket.createWebSocket();
ws.on('close', (err, value) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason);
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
```
### off('close')
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.
>**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.
> **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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -589,7 +585,6 @@ let ws = webSocket.createWebSocket();
ws.off('close');
```
### on('error')
on(type: 'error', callback: ErrorCallback): void
......@@ -603,26 +598,25 @@ Enables listening for the **error** events of a WebSocket connection. This API u
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------- |
| 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**
```js
let ws = webSocket.createWebSocket();
ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err))
console.log("on error, error:" + JSON.stringify(err))
});
```
### off('error')
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.
>**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.
> **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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -640,7 +634,6 @@ let ws = webSocket.createWebSocket();
ws.off('error');
```
## WebSocketRequestOptions
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
| ------ | ------ | ---- | ------------------------------------------------------------ |
| 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
Defines the optional parameters carried in the request for closing a WebSocket connection.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册