An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
...
...
@@ -14,40 +14,49 @@ For details about how to apply for permissions, see [Access Control Development]
The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
| request() | Initiates an HTTP request to a given URL. |
| request2()<sup>10+</sup> | Initiates an HTTP network request based on the URL and returns a streaming response.|
| destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.|
| on\('dataReceive'\)<sup>10+</sup> | Registers an observer for events indicating receiving of HTTP streaming responses. |
| off\('dataReceive'\)<sup>10+</sup> | Unregisters the observer for events indicating receiving of HTTP streaming responses. |
| on\('dataEnd'\)<sup>10+</sup> | Registers an observer for events indicating completion of receiving HTTP streaming responses. |
| off\('dataEnd'\)<sup>10+</sup> | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.|
| on\('dataProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
| off\('dataProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop
1. Import the required HTTP module.
2. Create an **HttpRequest** object.
3. (Optional) Listen for HTTP Response Header events.
4. Initiate an HTTP request to a given URL.
5. (Optional) Process the HTTP Response Header event and the return result of the HTTP request.
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned result based on service requirements.
6. Call **off()** to unsubscribe from HTTP response header events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
```js
// Import the http namespace.
importhttpfrom'@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
lethttpRequest=http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
// 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));
});
httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData.
// 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 the header field based on service requirements.
// You can add header fields based on service requirements.
header:{
'Content-Type':'application/json'
},
...
...
@@ -55,21 +64,33 @@ httpRequest.request(
extraData:{
"data":"data to send",
},
connectTimeout:60000,// Optional. The default value is 60000, in ms.
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.
usingProxy:false,// Optional. By default, network proxy is not used. This field is supported since API 10.
},(err,data)=>{
if(!err){
// data.result contains the HTTP response. Parse the response based on service requirements.
console.info('Result:'+data.result);
console.info('code:'+data.responseCode);
// data.header contains the HTTP response header. Parse the content based on service requirements.
// data.result carries the HTTP response. Parse the response based on service requirements.
The Socket Connection module allows an application to transmit data over a Socket connection through the TCP, UDP, or TLS protocol.
Your application can transmit data through Socket connections. Currently, the TCP and UDP protocols are supported.
## Basic Concepts
- Socket: An abstraction of endpoints for bidirectional communication between application processes running on different hosts in a network.
- TCP: Transmission Control Protocol, which is a byte stream–based transport layer communication protocol that is connection-oriented and reliable.
- UDP: User Datagram Protocol, which is a simple datagram-oriented transport layer communication protocol.
- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs.
## When to Use
Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows:
- Implementing data transmission over TCP/UDP Socket connections
- Implementing encrypted data transmission over TLS Socket connections
## Available APIs
The Socket connection function is mainly implemented by the Socket module. The following table describes the related APIs.
For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md).
Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs.
| API| Description|
| API| Description|
| -------- | -------- |
| constructUDPSocketInstance() | Creates a **UDPSocket** object.|
| constructTCPSocketInstance() | Creates a **TCPSocket** object.|
| bind() | Binds the IP address and port number.|
| constructUDPSocketInstance() | Creates a **UDPSocket** object.|
| constructTCPSocketInstance() | Creates a **TCPSocket** object.|
| bind() | Binds the IP address and port number.|
| send() | Sends data.|
| close() | Closes a Socket connection.|
| getState() | Obtains the Socket connection status.|
| connect() | Connects to the specified IP address and port. This function is supported only for TCP.|
| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.|
| on(type: 'message') | Enables listening for **message** events of the Socket connection. |
| off(type: 'message') | Disables listening for **message** events of the Socket connection. |
| on(type: 'close') | Enables listening for **close** events of the Socket connection. |
| off(type: 'close') | Disables listening for **close** events of the Socket connection. |
| on(type: 'error') | Enables listening for **error** events of the Socket connection. |
| off(type: 'error') | Disables listening for **error** events of the Socket connection. |
| on(type: 'listening') | Enables listening for **listening** events of the UDPSocket connection. |
| off(type: 'listening') | Disables listening for **listening** events of the UDPSocket connection. |
| on(type: 'connect') | Enables listening for **connect** events of the TCPSocket connection. |
| off(type: 'connect') | Disables listening for **connect** events of the TCPSocket connection. |
| close() | Closes a Socket connection.|
| getState() | Obtains the Socket connection status.|
| connect() | Connects to the specified IP address and port. This function is supported only for TCP.|
| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.|
| on(type: 'message') | Subscribes to **message** events of the Socket connection.|
| off(type: 'message') | Unsubscribes from **message** events of the Socket connection.|
| on(type: 'close') | Subscribes to **close** events of the Socket connection.|
| off(type: 'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type: 'error') | Subscribes to **error** events of the Socket connection.|
| off(type: 'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type: 'listening') | Subscribes to **listening** events of the UDP Socket connection. |
| off(type: 'listening') | Unsubscribes from **listening** events of the UDP Socket connection. |
| on(type: 'connect') | Subscribes to **connect** events of the TCP Socket connection. |
| off(type: 'connect') | Unsubscribes from **connect** events of the TCP Socket connection.|
TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
| API| Description|
| -------- | -------- |
| constructTLSSocketInstance() | Creates a **TLSSocket** object.|
| bind() | Binds the IP address and port number.|
| close(type: 'error') | Closes a Socket connection.|
| connect() | Sets up a connection to the specified IP address and port number.|
| 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.|
| 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: 'close') | Unsubscribes from **close** events of the TLS Socket connection.|
| off(type: 'error') | Unsubscribes from **error** events of the TLS Socket connection.|
| off(type: 'message') | Unsubscribes from **message** events of the TLS Socket connection.|
| on(type: 'close') | Subscribes to **close** events of the TLS Socket connection.|
| on(type: 'error') | Subscribes to **error** events of the TLS Socket connection.|
| on(type: 'message') | Subscribes to **message** events of the TLS Socket connection.|
| send() | Sends data.|
| setExtraOptions() | Sets other properties of the TLS Socket connection.|
## How to Develop
## Transmitting Data over TCP/UDP Socket Connections
The implementation is similar for UDPSocket and TCPSocket. The following uses the TCPSocket as an example.
The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example.
1. Import the required Socket module.
1. Import the required **socket** module.
2. Create a **TCPSocket** object.
3. (Optional) Enable listening for TCPSocket events.
3. (Optional) Subscribe to TCP Socket connection events.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
...
...
@@ -48,15 +85,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
6. Send data.
7. Enable the TCPSocket connection to be automatically closed after use.
7. Enable the TCPSocket connection to be automatically closed after use.
```js
importsocketfrom'@ohos.net.socket'
// Create a TCPSocket object.
lettcp=socket.constructTCPSocketInstance();
// Enable listening for TCPSocket events.
// Subscribe to TCP Socket connection events.
tcp.on('message',value=>{
console.log("on message")
letbuffer=value.message
...
...
@@ -73,7 +110,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.on('close',()=>{
console.log("on close")
});
// Bind the local IP address and port number.
letbindAddress={
address:'192.168.xx.xx',
...
...
@@ -86,6 +123,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return;
}
console.log('bind success');
// Set up a connection to the specified IP address and port number.
letconnectAddress={
address:'192.168.xx.xx',
...
...
@@ -100,6 +138,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return;
}
console.log('connect success');
// Send data.
tcp.send({
data:'Hello, server!'
...
...
@@ -112,7 +151,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
})
});
});
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket events.
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
setTimeout(()=>{
tcp.close((err)=>{
console.log('close socket.')
...
...
@@ -122,3 +162,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.off('close');
},30*1000);
```
## Implementing Encrypted Data Transmission over TLS Socket Connections
### How to Develop
TLS Socket connection process on the client:
1. Import the required **socket** module.
2. Bind the IP address and port number of the server.
3. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate.
4. Create a **TLSSocket** object.
5. (Optional) Subscribe to TLS Socket connection events.
6. Send data.
7. Enable the TLS Socket connection to be automatically closed after use.
```js
importsocketfrom'@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication).
| registerErrorObserver(observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.|
| unregisterErrorObserver(observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. |
| unregisterErrorObserver(observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. |
| on(type: "error", observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.|
| off(type: "error", observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. |
| off(type: "error", observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. |
When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result-codes-for-unregistering-an-observer).
When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#resultcodes-for-unregistering-an-observer).
**Table 2** Description of the ErrorObserver API
...
...
@@ -36,7 +36,7 @@ When an asynchronous callback is used, the return value can be processed directl
The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402.
The [intl](js-apis-intl.md) module provides basic i18n capabilities through the standard i18n APIs defined in ECMA 402. It works with the i18n module to provide a complete suite of i18n capabilities.
This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402.
The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities.
> **NOTE**
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - This module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. For details about the basic i18n capabilities, see [intl](js-apis-intl.md).
> - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md).
## Modules to Import
...
...
@@ -42,7 +42,7 @@ Obtains the localized script for the specified country.
**Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md).
For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message |
| ------ | ---------------------- |
...
...
@@ -81,7 +81,7 @@ Obtains the localized script for the specified language.
**Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md).
For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message |
| ------ | ---------------------- |
...
...
@@ -112,7 +112,7 @@ Obtains the list of system languages. For details about languages, see [Instanti
**Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md).
For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message |
| ------ | ---------------------- |
...
...
@@ -149,7 +149,7 @@ Obtains the list of countries and regions supported for the specified language.
**Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md).
For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message |
| ------ | ---------------------- |
...
...
@@ -187,7 +187,7 @@ Checks whether the system language matches the specified region.
**Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md).
For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message |
| ------ | ---------------------- |
...
...
@@ -218,7 +218,7 @@ Obtains the system language. For details about languages, see [Instantiating the
**Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md).
For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| flag | boolean | Yes | Whether to enable the local digit switch. The value **true** means to enable the local digit switch, and the value **false** indicates the opposite.|
| flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.|
**Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md).
For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message |
| ------ | ---------------------- |
...
...
@@ -687,7 +687,7 @@ Checks whether use of local digits is enabled.
**Error codes**
For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md).
For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message |
| ------ | ---------------------- |
...
...
@@ -1059,7 +1059,7 @@ Creates a **PhoneNumberFormat** object.
@@ -2363,7 +2363,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
getPreferredLanguageList(): Array<string>
Obtains the preferred language list.
Obtains the list of preferred languages.
This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [System.getPreferredLanguageList](#getpreferredlanguagelist9) instead.
...
...
@@ -2373,7 +2373,7 @@ This API is supported since API version 8 and is deprecated since API version 9.
| Type | Description |
| ------------------- | --------- |
| Array<string> | Preferred language list.|
| Array<string> | List of preferred languages.|
| locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).|
| options<sup>9+</sup> | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. |
| options<sup>9+</sup> | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. |
**Example**
```js
...
...
@@ -159,7 +159,7 @@ Minimizes information of the **Locale** object. If the script and locale informa
```
## LocaleOptions<sup>6+</sup>
## LocaleOptions<sup>9+</sup>
Represents the locale options.
...
...
@@ -206,7 +206,7 @@ Creates a **DateTimeOptions** object for the specified locale.
| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. |
| options<sup>9+</sup> | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. |
**Example**
```js
...
...
@@ -787,7 +787,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects.
```
## RelativeTimeFormatInputOptions<sup>8+</sup>
## RelativeTimeFormatInputOptions<sup>9+</sup>
Represents the properties of a **RelativeTimeFormat** object.
The **connection** module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information.
The network connection management module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information.
> **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.
## Modules to Import
...
...
@@ -10,6 +10,40 @@ The **connection** module provides basic network management capabilities. You ca
Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.
| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. |
| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.|
| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result.|
| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If the default activated data network is obtained successfully, err is undefined and data is the default activated data network. Otherwise, err is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
Obtains the default active data network in synchronous mode. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities.
...
...
@@ -76,59 +126,321 @@ Obtains the default active data network in synchronous mode. You can use [getNet
Obtains the global HTTP proxy configuration of the network. This API uses an asynchronous callback to return the result.
Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any.
| callback | AsyncCallback\<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **err** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getGlobalHttpProxy((error,data)=>{
console.info(JSON.stringify(error));
console.info(JSON.stringify(data));
})
```
## connection.getGlobalHttpProxy<sup>10+</sup>
getGlobalHttpProxy(): Promise\<HttpProxy>;
Obtains the global HTTP proxy configuration of the network. This API uses a promise to return the result.
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates that the default data network is activated.|
| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any.
Obtains information about the network bound to an application. This API uses an asynchronous callback to return the result.
| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If information about the network bound to the application is successfully obtained, **err** is **undefined** and **data** is the obtained network information. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getAppNet(function(error,data){
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## connection.getAppNet<sup>9+</sup>
getAppNet(): Promise\<NetHandle>;
Obtains information about the network bound to an application. This API uses a promise to return the result.
Binds an application to the specified network, so that the application can access the external network only through this network. This API uses an asynchronous callback to return the result.
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the application is successfully bound to the specified network, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
Binds an application to the specified network, so that the application can access the external network only through this network. This API uses a promise to return the result.
@@ -146,23 +458,30 @@ Obtains the list of all active data networks. This API uses an asynchronous call
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | Yes| Callback used to return the result.|
| callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | Yes| Callback used to return the result. If the list of all connected networks is obtained successfully, **err** is **undefined** and **data** is the list of activated data networks. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.|
| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. If the connection properties of the network corresponding to the **netHandle** is obtained successfully, **err** is **undefined** and **data** is the obtained network connection information. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.|
| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. If the capability information of the network corresponding to the **netHandle** is obtained successfully, **err** is **undefined** and **data** is the obtained network capability information. Otherwise, **err** is an error object. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any.
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates the default data network is activated.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.hasDefaultNet(function(error,data){
console.log(JSON.stringify(error))
console.log('data: '+data)
})
```
## connection.hasDefaultNet
hasDefaultNet(): Promise\<boolean>
Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any.
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the airplane mode is disabled successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.disableAirplaneMode(function(error){
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode
disableAirplaneMode(): Promise\<void>
Disables the airplane mode. This API uses a promise to return the result.
Reports connection of the data network. This API uses an asynchronous callback to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...
...
@@ -368,7 +947,17 @@ If this API is called, the application considers that the network connection sta
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback<void> | Yes| Callback used to return the result.|
| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the network status is reported successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
Reports connection of the data network. This API uses a promise to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...
...
@@ -399,11 +987,20 @@ If this API is called, the application considers that the network connection sta
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
Reports disconnection of the data network. This API uses an asynchronous callback to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...
...
@@ -432,7 +1027,17 @@ If this API is called, the application considers that the network connection sta
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback<void> | Yes| Callback used to return the result.|
| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the network status is reported successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
Reports disconnection of the data network. This API uses a promise to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...
...
@@ -464,11 +1067,20 @@ If this API is called, the application considers that the network connection sta
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
...
...
@@ -493,213 +1105,185 @@ Resolves the host name by using the default network to obtain all IP addresses.
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
| host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **err** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If a listener for network status changes is registered successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. |
| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If a listener for network status changes is unregistered successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Model restriction**: Before you call this API, make sure that you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
Registers a listener for **netCapabilitiesChange** events.
Registers a listener for **netBlockStatusChange** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
| type | string | Yes | Event type. The value is fixed at **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that network capabilities have changed.|
| callback | Callback<{netHandle:[NetHandle](#nethandle),netCap:[NetCapabilities](#netcapabilities)}> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | Yes | Callback used to return the network handle (**netHandle**) and network status (**blocked**).|
Registers a listener for **netConnectionPropertiesChange** events.
Registers a listener for **netCapabilitiesChange** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
| type | string | Yes | Event type. The value is fixed at **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback<{netHandle:[NetHandle](#nethandle),connectionProperties:[ConnectionProperties](#connectionproperties)}> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that the network capabilities have changed.|
| callback | Callback<{netHandle:[NetHandle](#nethandle),netCap:[NetCapabilities](#netcapabilities)}> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
Registers a listener for **netBlockStatusChange** events.
Registers a listener for **netConnectionPropertiesChange** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
| type | string | Yes | Event type. The value is fixed at **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback<{netHandle:[NetHandle](#nethandle),connectionProperties:[ConnectionProperties](#connectionproperties)}> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
| type | string | Yes | Event type. The value is fixed at**netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to**netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle (**netHandle**).|
Registers a listener for **netUnavailable** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket)\|[UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the **TCPSocket** or **UDPSocket** object is successfully bound to the current network, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| host | string | Yes | Host name to be resolved.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. |
| host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **err** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| host | string | Yes | Host name to be resolved.|
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. |
| host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the first IP address is obtained successfully, **err** is **undefined**, and **data** is the first obtained IP address. Otherwise, **err** is an error object. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. |
| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.|
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.|
| NET_CAPABILITY_INTERNET | 12 | The network has the Internet access capability, which is set by the network provider.|
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a virtual private network (VPN).|
| NET_CAPABILITY_VALIDATED | 16 | The Internet access capability of the network is successfully verified by the connection management module.|
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.|
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.|
| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.|
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).|
| NET_CAPABILITY_VALIDATED | 16 | The network is available. |
| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. |
| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|
The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
> **NOTE**<br>
> **NOTE**
> 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.
| iface | string | Yes | Name of the network interface. |
| iface | string | Yes | Interface name. |
| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.|
| Promise\<void> | Promise that returns no value.|
| Promise\<void> | Promise used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.|
| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. |
| iface | string | Yes | Interface name. If this parameter is left empty, the API checks for any active network interface. |
| callback | AsyncCallback\<number> | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.|
| Promise\<number> | Promise used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.|
| mode | [IPSetMode](#ipsetmode) | Yes | Configuration mode of the Ethernet connection.|
| ipAddr | string | Yes | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.|
| route | string | Yes | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| gateway | string | Yes | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| netMask | string | Yes | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | Yes | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).|
| mode | [IPSetMode](#ipsetmode) | Yes| Configuration mode of the Ethernet connection.|
| ipAddr | string | Yes| Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.|
| route | string | Yes| Route of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| gateway | string | Yes| Gateway of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| netMask | string | Yes| Subnet mask of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | Yes| DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).|
## IPSetMode
Defines the configuration mode of the Ethernet connection.
The **policy** module provides APIs for managing network policies, through which you can control and manage the data volume used.
> **NOTE**
>
> 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.
| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
| Promise\<void> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. If the operation is successful, **true** is returned, which means that applications running in the background are allowed to use mobile data. If the operation fails, an error message is returned.|
| Promise\<boolean> | Promise used to return the result. If the operation is successful, **true** is returned, which means that applications running in the background are allowed to use mobile data. If the operation fails, an error message is returned.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
| Promise\<void> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
| uid | number | Yes| Unique ID of the application.|
| callback | AsyncCallback\<[NetUidPolicy](#netuidpolicy)> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
| Promise\<[NetUidPolicy](#netuidpolicy)> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
Obtains the UID array of applications configured with a certain application-specific network policy. This API uses an asynchronous callback to return the result.
| callback | AsyncCallback\<Array\<number>> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
| Promise\<Array\<number>> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result.
Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result.
| uid | number | Yes| Unique ID of the application.|
| isMetered | boolean | Yes| Whether the network is a metered network.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that the application is allowed to access metered networks, and **false** means the opposite.|
| uid | number | Yes| Unique ID of the application.|
| iface | string | Yes| Name of the target network.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that the application is allowed to access the given network, and **false** means the opposite.|
Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result.
Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result.
| type | netUidPolicyChange | Yes| Event type. The value **netUidPolicyChange** indicates a policy change event.|
| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy) }> | Yes | Callback used to return the result. It is called when the registered network policy changes.|
| type | netUidRuleChange | Yes| Event type. The value **netUidRuleChange** indicates a rule change event.|
| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule) }> | Yes | Callback used to return the result. It is called when the registered rule changes.|
| type | netQuotaPolicyChange | Yes| Event type. The value **netQuotaPolicyChange** indicates a network quota policy change event.|
| callback | Callback\<Array\<[NetQuotaPolicy](#netquotapolicy)>> | Yes | Callback used to return the result. It is called when the registered network quota policy changes.|
| NET_BACKGROUND_POLICY_ENABLE | 1 | Applications running in the background are allowed to access metered networks.|
| NET_BACKGROUND_POLICY_DISABLE | 2 | Applications running in the background are not allowed to access metered networks.|
| NET_BACKGROUND_POLICY_ALLOW_LIST | 3 | Only applications on the allowlist are allowed to access metered networks when they are running in the background.|
The **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**<br>
> **NOTE**
>
> 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.
## Modules to Import
...
...
@@ -29,6 +30,15 @@ Checks whether network sharing is supported. This API uses an asynchronous callb
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
@@ -140,11 +175,27 @@ Starts network sharing of a specified type. This API uses an asynchronous callba
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
@@ -203,11 +270,25 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
@@ -495,11 +660,22 @@ Obtains the network sharing state of the specified type. This API uses an asynch
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.|
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
@@ -559,11 +746,22 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return an array of regular expressions.|
@@ -679,12 +900,18 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an
| type | string | Yes | Event name.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used to return the result.|
The **pointer** module provides APIs related to pointer attribute management.
> **NOTE**<br>
> **NOTE**
>
> 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.
## Modules to Import
...
...
@@ -237,6 +238,8 @@ Obtains the mouse movement speed. This API uses a promise to return the result.
@@ -19,8 +19,9 @@ Since API version 9, the stage model allows an application to obtain a **Resourc
For details about how to reference context in the stage model, see [Context in the Stage Model](../..//application-models/application-context-stage.md).
The **socket** module implements socket connection management and operation.
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
...
...
@@ -13,7 +12,7 @@ import socket from '@ohos.net.socket';
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
...
...
@@ -54,6 +53,13 @@ Binds the IP address and port number. The port number can be specified or random
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
...
...
@@ -84,11 +90,17 @@ Binds the IP address and port number. The port number can be specified or random
Sends data over a UDPSocket connection. This API uses an asynchronous callback to return the result.
...
...
@@ -123,6 +135,13 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```js
...
...
@@ -146,7 +165,7 @@ udp.send({
### send
send\(options: UDPSendOptions\): Promise<void\>
send(options: UDPSendOptions): Promise\<void\>
Sends data over a UDPSocket connection. This API uses a promise to return the result.
...
...
@@ -162,10 +181,17 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
@@ -346,6 +378,12 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
udp.off('listening',callback1);
udp.off('listening');
letcallback2=()=>{
console.log("on close, success");
}
udp.on('close',callback2);
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
udp.off('error',callback);
udp.off('error');
```
...
...
@@ -668,9 +712,15 @@ Defines information about the socket connection.
| port | number | Yes | Port number. The value ranges from **0** to **65535**. |
| size | number | Yes | Length of the server response message, in bytes. |
## Description of UDP Error Codes
The UDP error code mapping is in the format of 2301000 + Linux kernel error code.
For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md).
## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket
constructTCPSocketInstance(): TCPSocket
Creates a **TCPSocket** object.
...
...
@@ -679,7 +729,7 @@ Creates a **TCPSocket** object.
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
...
...
@@ -710,6 +760,12 @@ Binds the IP address and port number. The port number can be specified or random
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
...
...
@@ -744,9 +800,16 @@ Binds the IP address and port number. The port number can be specified or random
@@ -846,6 +926,13 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```js
...
...
@@ -870,12 +957,12 @@ promise.then(() => {
### send
send\(options: TCPSendOptions\): Promise<void\>
send(options: TCPSendOptions): Promise\<void\>
Sends data over a TCPSocket connection. This API uses a promise to return the result.
>**NOTE**<br/>
>This API can be called only after [connect](#connect) is successfully called.
>**NOTE**
>This API can be called only after **connect** is successfully called.
@@ -1150,6 +1277,13 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcp.off('connect',callback1);
tcp.off('connect');
letcallback2=()=>{
console.log("on close success");
}
tcp.on('close',callback2);
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcp.off('error',callback);
tcp.off('error');
```
...
...
@@ -1452,7 +1591,13 @@ Defines other properties of the TCPSocket connection.
| receiveBufferSize | number | No | Size of the receive buffer, in bytes. |
| sendBufferSize | number | No | Size of the send buffer, in bytes. |
| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. |
| socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. |
| socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms. |
## Description of TCP Error Codes
The TCP error code mapping is in the format of 2301000 + Linux kernel error code.
For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md).
## socket.constructTLSSocketInstance<sup>9+</sup>
...
...
@@ -1465,7 +1610,7 @@ Creates a **TLSSocket** object.
Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses an asynchronous callback to return the result.
Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses a promise to return the result.
...
...
@@ -1706,7 +1851,7 @@ Sets other properties of the TCPSocket connection after successful binding of th
Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses an asynchronous callback to return the result.
...
...
@@ -1767,7 +1912,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after
Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. Both two-way and one-way authentication modes are supported. This API uses a promise to return the result.
...
...
@@ -1857,7 +2001,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
...
...
@@ -1867,7 +2011,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.|
| callback | AsyncCallback\<[NetAddress](#netaddress)\> | Yes | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.|
Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
...
...
@@ -2018,7 +2161,7 @@ Obtains the local digital certificate after a TLSSocket connection is establishe
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.|
Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
...
...
@@ -2050,9 +2193,9 @@ Obtains the local digital certificate after a TLSSocket connection is establishe
**Return value**
| Type | Description |
| Type | Description |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.|
| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
...
...
@@ -2084,7 +2227,7 @@ Obtains the digital certificate of the server after a TLSSocket connection is es
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
...
...
@@ -2214,7 +2357,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc
Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses a promise to return the result.
...
...
@@ -2249,7 +2392,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc
Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
...
...
@@ -2282,7 +2425,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T
Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
...
...
@@ -2315,7 +2458,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T
| Type | Description |
| ---------------------- | -------------------- |
| Promise\<Array\<string>> | Promise used to return the result.|
| Promise\<Array\<string\>\> | Promise used to return the result.|
**Error codes**
...
...
@@ -2328,7 +2471,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T
> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.net.http`](js-apis-http.md) instead.
>
>
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...
...
@@ -15,7 +14,7 @@ import fetch from '@system.fetch';
```
## fetch.fetch
## fetch.fetch<sup>3+</sup>
fetch(Object): void
...
...
@@ -31,9 +30,9 @@ Obtains data through a network.
| header | Object | No| Request header.|
| method | string | No| Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**.|
| responseType | string | No| Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values in the **success** callback.|
| success | Function | No| Called when the data is obtained successfully. The return value is [FetchResponse](#fetchresponse). |
| fail | Function | No| Called when the data failed to be obtained.|
| complete | Function | No| Called when the execution is complete.|
| success | Function | No| Called when the API call is successful. The return value is defined by [FetchResponse](#fetchresponse).|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when the API call is complete.|
**Table 1** Mapping between data and Content-Type
...
...
@@ -46,11 +45,11 @@ Obtains data through a network.
## FetchResponse
| Name| Type| Description|
| -------- | -------- | -------- |
| code | number | Server status code.|
| data | string \| Object | The data type is determined by **responseType**. For details, see the mapping between **responseType** and **data** in **success** callback.|
| headers | Object | All headers in the response from the server.|
| data | string \| Object | Yes| No| The type of the returned data is determined by **responseType**. For details, see the mapping between **responseType** and **data** in **success** callback.|
| headers | Object | Yes| No| All headers in the response from the server.|
**Table 2** Mapping between responseType and data in success callback
...
...
@@ -85,8 +84,8 @@ export default {
```
> **NOTE**<br/>
> HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. That is:
> **NOTE**
> HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. That is:
> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead.
>
> **NOTE**
> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.telephony.observer`](js-apis-observer.md).
>
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...
...
@@ -31,17 +31,17 @@ Obtains the network type.
**Parameters**
| Name | Type | Mandatory | Description |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| success | Function | No | Called when the execution is successful. The return value is [FetchResponse](#fetchresponse). |
| fail | Function | No | Called when the operation fails. |
| complete | Function | No | Called when the execution is complete. |
| success | Function | No| Called when the API call is successful. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when the API call is complete.|
One of the following error codes will be returned if the operation fails.
One of the following error codes will be returned if the API call has failed.
| Error Code | Description |
| Error Code| Description|
| -------- | -------- |
| 602 | The current permission is not declared.|
| 602 | The current permission is not declared.|
**Example**
...
...
@@ -71,17 +71,17 @@ Listens to the network connection state. If this method is called multiple times
**Parameters**
| Name | Type | Mandatory | Description |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| success | Function | No | Called when the network connection state changes. The return value is [FetchResponse](#fetchresponse). |
| fail | Function | No | Called when the multimedia volume fails to be obtained. |
| success | Function | No| Called when the network state changes. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No| Called when API call has failed.|
One of the following error codes will be returned if the listening fails.
One of the following error codes will be returned if the API call has failed.
| Error Code | Description |
| Error Code| Description|
| -------- | -------- |
| 602 | The current permission is not declared.|
| 200 | The subscription fails. |
| 602 | The current permission is not declared.|
| 200 | Subscription failed.|
**Example**
...
...
@@ -122,7 +122,9 @@ export default {
## NetworkResponse
| Name | Type | Description |
| -------- | -------- | -------- |
| metered | boolean | Whether the billing is based on the data volume. |
| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. |
@@ -8,8 +8,10 @@ There are two types of updates: SD card update and over the air (OTA) update.
- The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer.
> **NOTE**
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs provided by this module are system APIs.
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs provided by this module are system APIs.
## Modules to Import
...
...
@@ -2034,7 +2036,7 @@ Enumerates update states.
| WAITING_INSTALL | 30 | Waiting for installation. |
| UPDATING | 31 | Updating. |
| WAITING_APPLY | 40 | Waiting for applying the update. |
The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side.
The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side.
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md) instead.
>
> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md).
## Modules to Import
...
...
@@ -30,7 +32,7 @@ Obtains the list of USB devices connected to the host. If no device is connected
Connects to a USB device based on the device list obtained by using**getDevices()**.
Connects to the USB device based on the device information returned by**getDevices()**.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission.
...
...
@@ -119,13 +121,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode
Checks whether the application has the permission to access the device.
The value **true** is returned if the device access permission is available; the value **false** is returned otherwise.
Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise.
The **webSocket** module implements WebSocket connection management and operation.
> **NOTE**<br>
> **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.
...
...
@@ -17,7 +16,7 @@ If an error occurs in any of the preceding processes, the client will receive a
importwebSocketfrom'@ohos.net.webSocket';
```
## Complete Example
## Examples
```js
importwebSocketfrom'@ohos.net.webSocket';
...
...
@@ -37,7 +36,7 @@ ws.on('open', (err, value) => {
});
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.
// When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
Creates a WebSocket connection. You can use this API to create or close a WebSocket connection, send data over it, or enable or disable listening for the **open**, **close**, **message**, and **error** events.
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.|
| data | string \| ArrayBuffer | Yes | Data to send.<br>Only the string type is supported for API version 6 or earlier. Both the string and ArrayBuffer types are supported for API version 8 or later.|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
@@ -245,14 +270,21 @@ Sends data through a WebSocket connection. This API uses a promise to return the
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------ |
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.|
| data | string \| ArrayBuffer | Yes | Data to send.<br>Only the string type is supported for API version 6 or earlier. Both the string and ArrayBuffer types are supported for API version 8 or later.|
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
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.
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
>**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.
| type | string | Yes | Event type. <br/>**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{code:number,reason:string}> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<{ code: number, reason: string }\> | Yes | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
**Example**
```js
letws=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);
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
| type | string | Yes | Event type. <br/>**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{code:number,reason:string}> | No | Callback used to return the result. |
| callback | AsyncCallback\<{ code: number, reason: string }\> | No | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
>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.
This error code is reported if an operation is not allowed.
**Cause**
The operation is illegal.
**Procedure**
Check the operation procedure.
## 2301002 File Not Exist
**Error Message**
No such file or directory.
**Description**
This error code is reported if the requested file does not exist.
**Cause**
The requested file does not exist.
**Procedure**
Check the file name or file path.
## 2301003 Process Not Exist
**Error Message**
No such process.
**Description**
This error code is reported if a process does not exist.
**Cause**
The process does not exist.
**Procedure**
Check the process information.
## 2301004 System Call Interrupted
**Error Message**
Interrupted system call.
**Description**
This error code is reported if the system call is interrupted.
**Cause**
The system call is interrupted.
**Procedure**
Rectify system call errors.
**Description of TCP/UDP error codes:**
> Mapping format of other TCP/UDP Socket error codes: 2301000 + Linux kernel error code (errno). For details, see Linux kernel error codes.
## 2300002 System Internal Error
**Error Message**
System internal error.
**Description**
This error code is reported if a system internal error occurs.
**Cause**
1. The memory is abnormal.
2. A null pointer is present.
**Procedure**
1. Check whether the memory space is sufficient. If not, clear the memory and try again.
2. Check whether the system is normal. If not, try again later or restart the device.
## 2303104 System Call Interrupted
**Error Message**
Interrupted system call.
**Description**
This error code is reported if the system call is interrupted.
**Cause**
Calling the **connect** function may result in a long blocking time. In such a case, the system generates an interrupt signal and returns an **EINTR** error.
**Procedure**
Call the **connect** function to try network connection again.
## 2303109 Error File Number
**Error Message**
Bad file number.
**Description**
This error code is reported if an operation is performed on a locally closed socket.
This error code is reported if the requested system resource is temporarily unavailable.
**Cause**
The system resources are in use.
**Procedure**
Try again later.
## 2303188 Socket Operations on Non-Sockets
**Error Message**
Socket operation on non-socket.
**Description**
This error code is reported if a socket descriptor is not specified for the **socket** parameter.
**Cause**
A socket descriptor is not specified for the **socket** parameter.
**Procedure**
Check whether the descriptor is correctly obtained.
## 2303191 Incorrect Socket Protocol Type
**Error Message**
Protocol wrong type for socket.
**Description**
This error code is reported if the type of the specified socket protocol is incorrect.
**Cause**
The **socket** function is called with an unsupported socket protocol type.
For example, the protocol type cannot be set to **SOCK_STREAM socket** for the the Internet UDP protocol.
**Procedure**
Check whether the socket protocol type is correct.
## 2303198 Network Address Already In Use
**Error Message**
Address already in use.
**Description**
This error code is reported if a network address has been used.
**Cause**
The probable cause can be any of the following: The application attempts to bind a socket to an IP address/port that has been used for an existing socket. The socket is not properly closed. The socket is still being closed.
**Procedure**
Try another network address.
## 2303199 Failed to Assign the Requested Address
**Error Message**
Cannot assign requested address.
**Description**
This error code is reported if the requested address is invalid in its context.
**Cause**
The remote address or port is invalid for the remote server.
**Procedure**
Check whether the address or port is correct.
## 2303210 Connection Timeout
**Error Message**
Connection timed out.
**Description**
This error code is reported if the connection to the remote server cannot be set up for a long time.
**Cause**
It is probable that a server breakdown has occurred.
**Procedure**
Contact the peer end to rectify the fault.
## 2303501 Null SSL
**Error Message**
SSL is null.
**Description**
This error code is reported if the SSL is null.
**Cause**
The returned error information is null when an internal function fails to be executed.
**Procedure**
Call the function again.
## 2303502 TLS Reading Error
**Error Message**
Error in tls reading.
**Description**
This error code is reported if an error occurs while reading data on the TLS socket.
**Cause**
The underlying socket is blocked.
**Procedure**
Perform data receiving again.
## 2303503 TLS Writing Error
**Error Message**
Error in tls writing.
**Description**
This error code is reported if an error occurs while writing data on the TLS socket.
**Cause**
When the send buffer is full, the underlying socket sends an **EWOUDLBLOCK** error, which means that the server does not read the data sent from the client.
**Procedure**
Rectify the fault on the server side.
## 2303504 x509 Failed to Look Up the x509 Certificate
**Error Message**
Error looking up x509.
**Description**
An error occurred when verifying the x509 certificate.
**Cause**
The local certificate does not match the server certificate.
**Procedure**
Check whether the local CA matches the server certificate.
## 2303505 TLS System Call Error
**Error Message**
Error occurred in the tls system call.
**Description**
This error code is reported if the TLS system call fails because of fatal I/O errors.
**Cause**
Network communication fails because of network faults.
**Procedure**
For details, see the Linux kernel error codes (errno).
## 2303506 Failed to Close TLS Connections
**Error Message**
Error clearing tls connection.
**Description**
This error code is reported if the TLS/SSL connection to be closed has been disabled.
**Cause**
The TLS/SSL connection to be closed has been disabled.
@@ -7,20 +7,17 @@ HiTraceMeter is the OpenHarmony subsystem that provides APIs to implement call c
## Basic Concepts
The HiTraceMeter subsystem consists of three parts:
- JS/C++ HiTraceMeter APIs for application logging
- hitrace CLI tool for data collection
- smartperf tool for graphical data analysis
Wherein, HiTraceMeter APIs and the hitrace CLI tool run on the device side, and the smartperf tool runs on the PC side.
HiTraceMeter APIs are provided in C++ and JS for event logging, which aims to generate the trace data necessary for performance tracing and analysis during the development process.
Wherein, HiTraceMeter APIs and the hitrace CLI tool run on the device side, and the smartperf tool runs on the PC side. HiTraceMeter APIs are provided in C++ and JS for event logging, which aims to generate the trace data necessary for performance tracing and analysis during the development process.
The hitrace CLI tool is used to collect trace data. It captures trace data flows and saves the data as a text file.
The smartperf tool allows you to perform data analysis manually or use the analysis script for automated data analysis. If you want to get the data analysis done automatically, you need to supply the data file generated by the hitrace CLI tool as the input for the smartperf tool.
Traces data is classified by trace tag or trace category. Generally, one device subsystem corresponds to one tag. The tag is passed as the **Tag** parameter to event logging APIs. When you use the hitrace CLI tool to collect trace data, only the trace data specified by the **Tag** parameter is collected. Trace data of applications is fixedly labeled as **APP Tag**, and therefore, no **Tag** parameter needs to be passed to JS APIs. The following is a list of trace tags supported by HiTraceMeter. You can view the tags in [hitrace_meter.h](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h).
Traces data is classified by trace tag or trace category. Generally, one device subsystem corresponds to one tag. The tag is passed as the **Tag** parameter to event logging APIs. When you use the hitrace CLI tool to collect trace data, only the trace data specified by the **Tag** parameter is collected. Trace data of applications is fixedly labeled as **APP Tag**, and therefore, no **Tag** parameter needs to be passed to JS APIs. The following is a list of trace tags supported by HiTraceMeter. You can view the tags in [hitrace_meter.h](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h).
```cpp
constexpruint64_tHITRACE_TAG_NEVER=0;// This tag is never enabled.
HiTraceMeter provides the hitrace CLI tool for capturing trace data in user mode and kernel mode, and provides C++ (innerkits) and JS (kits) APIs for event logging in user mode. Through extending kernel's ftrace functionality, HiTraceMeter can use the trace_marker node of ftrace to write the data, which is written into the user space by event logging APIs, to the kernel buffer. The following figure shows the basic HiTraceMeter architecture.
...
...
@@ -109,7 +106,7 @@ Only C++ APIs are now open for system developers. If you're developing a JS app,
| void StartTrace(uint64_t label, const std::string& value, float limit = -1); | Starts a synchronous trace.|**label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.|
| void StartAsyncTrace(uint64_t label, const std::string& value, int32_t taskId, float limit = -1); | Starts an asynchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.<br>**taskId**: ID used to indicate the association of APIs in an asynchronous trace.|
| void FinishAsyncTrace(uint64_t label, const std::string& value, int32_t taskId); | Stops an asynchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.<br>**taskId**: ID used to indicate the association of APIs in an asynchronous trace.|
...
...
@@ -130,9 +127,9 @@ The trace data of **StartAsyncTrace** and **FinishAsyncTrace** is matched based
**Table 3** Counter APIs
| API | Function |Parameter Description |
| Counter Trace | Function |Parameter Description |
| void CountTrace(uint64_t label, const std::string& name, int64_t); | Performs a count trace.|**label**: trace category.<br>**name**: trace name displayed in the IDE.|
| void CountTrace(uint64_t label, const std::string& name, int64_t); | Count trace.|**label**: trace category.<br>**name**: trace name displayed in the IDE.|
## How to Develop
...
...
@@ -147,33 +144,8 @@ The trace data of **StartAsyncTrace** and **FinishAsyncTrace** is matched based
#include "hitrace_meter.h"// Header file for defining APIs
```
3. When calling an API, pass the trace value as an input parameter. After the hitrace command is executed in the shell, the trace data is automatically captured. The captured data includes the function call process and the memory and time consumed during this process. You can use the data to analyze the call process to identify performance problems.
StartTrace(label, "func1Trace", -1); // Trace start point of func1Start
FinishTrace(label); // Trace end point of func1Trace
StartAsyncTrace(label, "asyncTrace1", 1234); // Start point of asyncTrace1
FinishAsyncTrace(label, "asyncTrace2", 3456); // End point of asyncTrace2
```
4. On completion of HiTraceMeter building and deployment, start a trace. After you run the application in the shell on the device, trace data will be captured automatically.
You can open the captured data by clicking **Open trace file** in the smartperf tool or dragging the data to the graphics area. For details, see [smartperf](https://toscode.gitee.com/openharmony-sig/smartperf).
## Development Example
3. When calling an API, pass the trace value as an input parameter. The trace tags currently supported are listed in **hitrace_meter.h**. Assume that the trace tag is **OHOS** and trace data of **func1** and **func2** needs to be captured. After the hitrace command is executed in the shell, the trace data is automatically captured. The captured data includes the function call process and the memory and time consumed during this process. You can use the data to analyze the call process to identify performance problems.
You can access a full list of trace tags supported by HiTraceMeter in **hitrace_meter.h**. The following uses the **OHOS** tag as an example to illustrate how to obtain the trace data of the **func1** and **func2** functions.
```cpp
#include "hitrace_meter.h" // Include hitrace_meter.h
...
...
@@ -192,11 +164,21 @@ int main()
FinishTrace(label);// Trace end point of func2Trace
sleep(1);
FinishTrace(label);// Trace end point of func1Trace
StartAsyncTrace(label,"asyncTrace1",1234);// Trace start point of asyncTrace1
FinishAsyncTrace(label,"asyncTrace1",1234);// Trace end point of asyncTrace2
return0;
}
```
}
```
4. On completion of HiTraceMeter building and deployment, start a trace. After you run the application in the shell on the device, trace data will be captured automatically.
You can open the captured data by clicking **Open trace file** in the smartperf tool or dragging the data to the graphics area. For details, see [smartperf](https://toscode.gitee.com/openharmony-sig/smartperf).
## Verification
...
...
@@ -313,7 +295,7 @@ Examples:
hitrace -l
```
Or,
Alternatively, run the following command:
```
hitrace --list_categories
...
...
@@ -356,6 +338,6 @@ Examples:
# References
# Reference
For details about HiTraceMeter, see [hiviewdfx_hitrace: A Lightweight Distributed Tracing](https://gitee.com/openharmony/hiviewdfx_hitrace).
1. Import the HTTP namespace from **@ohos.net.http.d.ts**.
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Call **httpRequest.on()** to subscribe to an HTTP response header. This method returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
3. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned result based on service requirements.
6. Call **httpRequest.destroy()** to release resources after the request is processed.
6. Call **off()** to unsubscribe from HTTP response header events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
```
// Import the HTTP namespace.
// Import the http namespace.
import http from '@ohos.net.http';
// Each httpRequest corresponds to an HttpRequestTask object and cannot be reused.
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than the response to httpRequest.
httpRequest.on('headersReceive', (data) => {
console.info('header: ' + data.header);
// 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.
// Set the URL for the httpRequest. You must specify the URL address, and set httpRequestOptions as required. You can specify the parameters for GET in extraData.
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: 'POST', // Optional. The default value is GET.
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'
...
...
@@ -127,21 +122,28 @@ httpRequest.request(
extraData: {
"data": "data to send",
},
connectTimeout: 60000, // This parameter is optional. The default value is 60000, that is, 60s.
readTimeout: 60000, // This parameter is optional. The default value is 60000, that is, 60s.
},(err, data) => {
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.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
}, (err, data) => {
if (!err) {
// data.result carries the HTTP response. Parse the response based on service requirements.