提交 887f515f 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 f4869166
...@@ -67,7 +67,7 @@ httpRequest.request( ...@@ -67,7 +67,7 @@ httpRequest.request(
## http.createHttp ## http.createHttp
createHttp\(\): HttpRequest createHttp(): HttpRequest
Creates an HTTP request. You can use this API to initiate or destroy an HTTP request, or enable or disable listening for HTTP Response Header events. An HttpRequest object corresponds to an HTTP request. To initiate multiple HTTP requests, you must create an **HttpRequest** object for each HTTP request. Creates an HTTP request. You can use this API to initiate or destroy an HTTP request, or enable or disable listening for HTTP Response Header events. An HttpRequest object corresponds to an HTTP request. To initiate multiple HTTP requests, you must create an **HttpRequest** object for each HTTP request.
...@@ -77,7 +77,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req ...@@ -77,7 +77,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req
| Type | Description | | Type | Description |
| :---------- | :----------------------------------------------------------- | | :---------- | :----------------------------------------------------------- |
| HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.| | HttpRequest | An **HttpRequest** object, which contains the **request**, **request2**, **destroy**, **on**, or **off** method.|
**Example** **Example**
...@@ -88,14 +88,17 @@ let httpRequest = http.createHttp(); ...@@ -88,14 +88,17 @@ let httpRequest = http.createHttp();
## HttpRequest ## HttpRequest
Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp()](#httpcreatehttp) to create an **HttpRequestTask** object.
### request ### request
request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void request(url: string, callback: AsyncCallback\<HttpResponse\>):void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -140,10 +143,13 @@ httpRequest.request("EXAMPLE_URL", (err, data) => { ...@@ -140,10 +143,13 @@ httpRequest.request("EXAMPLE_URL", (err, data) => {
### request ### request
request\(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpResponse\>\):void request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpResponse\>):void
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -223,10 +229,13 @@ httpRequest.request("EXAMPLE_URL", ...@@ -223,10 +229,13 @@ httpRequest.request("EXAMPLE_URL",
### request ### request
request\(url: string, options? : HttpRequestOptions\): Promise\<HttpResponse\> request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -309,7 +318,7 @@ promise.then((data) => { ...@@ -309,7 +318,7 @@ promise.then((data) => {
### destroy ### destroy
destroy\(\): void destroy(): void
Destroys an HTTP request. Destroys an HTTP request.
...@@ -323,7 +332,7 @@ httpRequest.destroy(); ...@@ -323,7 +332,7 @@ httpRequest.destroy();
### request2<sup>10+</sup> ### request2<sup>10+</sup>
request2(url: string, callback: AsyncCallback<void>): void request2(url: string, callback: AsyncCallback\<void\>): void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
...@@ -359,7 +368,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ...@@ -359,7 +368,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
```js ```js
httpRequest.request2("EXAMPLE_URL", (err) => { httpRequest.request2("EXAMPLE_URL", (err) => {
if (!err) { if (!err) {
console.info(request2 OK!); console.info("request2 OK!");
} else { } else {
console.info("request2 ERROR : err = " + JSON.stringify(err)); console.info("request2 ERROR : err = " + JSON.stringify(err));
} }
...@@ -368,9 +377,9 @@ httpRequest.request2("EXAMPLE_URL", (err) => { ...@@ -368,9 +377,9 @@ httpRequest.request2("EXAMPLE_URL", (err) => {
### request2<sup>10+</sup> ### request2<sup>10+</sup>
request2(url: string, options: HttpRequestOptions, callback: AsyncCallback<void>): void request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\<void\>): void
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -437,7 +446,7 @@ httpRequest.request2("EXAMPLE_URL", ...@@ -437,7 +446,7 @@ httpRequest.request2("EXAMPLE_URL",
connectTimeout: 60000 connectTimeout: 60000
}, (err) => { }, (err) => {
if (!err) { if (!err) {
console.info(request2 OK!); console.info("request2 OK!");
} else { } else {
console.info("request2 ERROR : err = " + JSON.stringify(err)); console.info("request2 ERROR : err = " + JSON.stringify(err));
} }
...@@ -445,7 +454,7 @@ httpRequest.request2("EXAMPLE_URL", ...@@ -445,7 +454,7 @@ httpRequest.request2("EXAMPLE_URL",
``` ```
### request2<sup>10+</sup> ### request2<sup>10+</sup>
request2\(url: string, options? : HttpRequestOptions\): Promise\<void\> request2(url: string, options? : HttpRequestOptions): Promise\<void\>
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response. Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response.
...@@ -518,20 +527,20 @@ let promise = httpRequest.request("EXAMPLE_URL", { ...@@ -518,20 +527,20 @@ let promise = httpRequest.request("EXAMPLE_URL", {
} }
}); });
promise.then(() => { promise.then(() => {
console.info(request2 OK!); console.info("request2 OK!");
}).catch((err) => { }).catch((err) => {
console.info("request2 ERROR : err = " + JSON.stringify(err)); console.info("request2 ERROR : err = " + JSON.stringify(err));
}); });
``` ```
### on\('headerReceive'\) ### on('headerReceive')
on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void
Registers an observer for HTTP Response Header events. Registers an observer for HTTP Response Header events.
>**NOTE** >**NOTE**
>This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead. >This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8) instead.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -545,24 +554,20 @@ Registers an observer for HTTP Response Header events. ...@@ -545,24 +554,20 @@ Registers an observer for HTTP Response Header events.
**Example** **Example**
```js ```js
httpRequest.on('headerReceive', (err, data) => { httpRequest.on('headerReceive', (data) => {
if (!err) { console.info('error:' + JSON.stringify(data));
console.info('header: ' + JSON.stringify(data));
} else {
console.info('error:' + JSON.stringify(err));
}
}); });
``` ```
### off\('headerReceive'\) ### off('headerReceive')
off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>**NOTE** >**NOTE**
> >
>1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead. >1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8) instead.
> >
>2. 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. >2. 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.
...@@ -581,9 +586,9 @@ Unregisters the observer for HTTP Response Header events. ...@@ -581,9 +586,9 @@ Unregisters the observer for HTTP Response Header events.
httpRequest.off('headerReceive'); httpRequest.off('headerReceive');
``` ```
### on\('headersReceive'\)<sup>8+</sup> ### on('headersReceive')<sup>8+</sup>
on\(type: 'headersReceive', callback: Callback<Object\>\): void on(type: 'headersReceive', callback: Callback\<Object\>): void
Registers an observer for HTTP Response Header events. Registers an observer for HTTP Response Header events.
...@@ -604,9 +609,9 @@ httpRequest.on('headersReceive', (header) => { ...@@ -604,9 +609,9 @@ httpRequest.on('headersReceive', (header) => {
}); });
``` ```
### off\('headersReceive'\)<sup>8+</sup> ### off('headersReceive')<sup>8+</sup>
off\(type: 'headersReceive', callback?: Callback<Object\>\): void off(type: 'headersReceive', callback?: Callback\<Object\>): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
...@@ -628,9 +633,9 @@ Unregisters the observer for HTTP Response Header events. ...@@ -628,9 +633,9 @@ Unregisters the observer for HTTP Response Header events.
httpRequest.off('headersReceive'); httpRequest.off('headersReceive');
``` ```
### once\('headersReceive'\)<sup>8+</sup> ### once('headersReceive')<sup>8+</sup>
once\(type: 'headersReceive', callback: Callback<Object\>\): void once(type: 'headersReceive', callback: Callback\<Object\>): void
Registers a one-time observer for HTTP Response Header events. Once triggered, the observer will be removed. This API uses an asynchronous callback to return the result. Registers a one-time observer for HTTP Response Header events. Once triggered, the observer will be removed. This API uses an asynchronous callback to return the result.
...@@ -650,9 +655,9 @@ httpRequest.once('headersReceive', (header) => { ...@@ -650,9 +655,9 @@ httpRequest.once('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
``` ```
### on\('dataReceive'\)<sup>10+</sup> ### on('dataReceive')<sup>10+</sup>
on\(type: 'dataReceive', callback: Callback\<ArrayBuffer\>\): void on(type: 'dataReceive', callback: Callback\<ArrayBuffer\>): void
Registers an observer for events indicating receiving of HTTP streaming responses. Registers an observer for events indicating receiving of HTTP streaming responses.
...@@ -673,9 +678,9 @@ httpRequest.on('dataReceive', (data) => { ...@@ -673,9 +678,9 @@ httpRequest.on('dataReceive', (data) => {
}); });
``` ```
### off\('dataReceive'\)<sup>10+</sup> ### off('dataReceive')<sup>10+</sup>
off\(type: 'dataReceive', callback?: Callback\<ArrayBuffer\>\): void off(type: 'dataReceive', callback?: Callback\<ArrayBuffer\>): void
Unregisters the observer for events indicating receiving of HTTP streaming responses. Unregisters the observer for events indicating receiving of HTTP streaming responses.
...@@ -697,9 +702,9 @@ Unregisters the observer for events indicating receiving of HTTP streaming respo ...@@ -697,9 +702,9 @@ Unregisters the observer for events indicating receiving of HTTP streaming respo
httpRequest.off('dataReceive'); httpRequest.off('dataReceive');
``` ```
### on\('dataEnd'\)<sup>10+</sup> ### on('dataEnd')<sup>10+</sup>
on\(type: 'dataEnd', callback: Callback\<void\>\): void on(type: 'dataEnd', callback: Callback\<void\>): void
Registers an observer for events indicating completion of receiving HTTP streaming responses. Registers an observer for events indicating completion of receiving HTTP streaming responses.
...@@ -720,7 +725,7 @@ httpRequest.on('dataReceive', () => { ...@@ -720,7 +725,7 @@ httpRequest.on('dataReceive', () => {
}); });
``` ```
### off\('dataEnd'\)<sup>10+</sup> ### off('dataEnd')<sup>10+</sup>
off(type: 'dataEnd', callback?: Callback\<void\>): void off(type: 'dataEnd', callback?: Callback\<void\>): void
...@@ -744,9 +749,9 @@ Unregisters the observer for events indicating completion of receiving HTTP stre ...@@ -744,9 +749,9 @@ Unregisters the observer for events indicating completion of receiving HTTP stre
httpRequest.off('dataEnd'); httpRequest.off('dataEnd');
``` ```
### on\('dataProgress'\)<sup>10+</sup> ### on('dataProgress')<sup>10+</sup>
on\(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>\): void on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void
Registers an observer for events indicating progress of receiving HTTP streaming responses. Registers an observer for events indicating progress of receiving HTTP streaming responses.
...@@ -757,19 +762,17 @@ Registers an observer for events indicating progress of receiving HTTP streaming ...@@ -757,19 +762,17 @@ Registers an observer for events indicating progress of receiving HTTP streaming
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | --------------------------------- | | -------- | ----------------------- | ---- | --------------------------------- |
| type | string | Yes | Event type. The value is **dataProgress**.| | type | string | Yes | Event type. The value is **dataProgress**.|
| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.<br>**receiveSize**: number of received bytes.<br>**totalSize**: total number of bytes to be received.|
**Example** **Example**
```js ```js
httpRequest.on('dataProgress', (data) => { httpRequest.on('dataProgress', (data) => {
if (!err) {
console.info('dataProgress:' + JSON.stringify(data)); console.info('dataProgress:' + JSON.stringify(data));
}
}); });
``` ```
### off\('dataProgress'\)<sup>10+</sup> ### off('dataProgress')<sup>10+</sup>
off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void
...@@ -915,11 +918,11 @@ let httpResponseCache = http.createHttpResponseCache(); ...@@ -915,11 +918,11 @@ let httpResponseCache = http.createHttpResponseCache();
## HttpResponseCache<sup>9+</sup> ## HttpResponseCache<sup>9+</sup>
Defines an object that stores the response to an HTTP request. Defines an object that stores the response to an HTTP request. Before invoking APIs provided by **HttpResponseCache**, you must call [createHttpResponseCache()](#httpcreatehttpresponsecache9) to create an **HttpRequestTask** object.
### flush<sup>9+</sup> ### flush<sup>9+</sup>
flush(callback: AsyncCallback\<void>): void flush(callback: AsyncCallback\<void\>): void
Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses an asynchronous callback to return the result. Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses an asynchronous callback to return the result.
...@@ -929,7 +932,7 @@ Flushes data in the cache to the file system so that the cached data can be acce ...@@ -929,7 +932,7 @@ Flushes data in the cache to the file system so that the cached data can be acce
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -945,7 +948,7 @@ httpResponseCache.flush(err => { ...@@ -945,7 +948,7 @@ httpResponseCache.flush(err => {
### flush<sup>9+</sup> ### flush<sup>9+</sup>
flush(): Promise\<void> flush(): Promise\<void\>
Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses a promise to return the result. Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses a promise to return the result.
...@@ -955,7 +958,7 @@ Flushes data in the cache to the file system so that the cached data can be acce ...@@ -955,7 +958,7 @@ Flushes data in the cache to the file system so that the cached data can be acce
| Type | Description | | Type | Description |
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void>> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Example** **Example**
...@@ -969,7 +972,7 @@ httpResponseCache.flush().then(() => { ...@@ -969,7 +972,7 @@ httpResponseCache.flush().then(() => {
### delete<sup>9+</sup> ### delete<sup>9+</sup>
delete(callback: AsyncCallback\<void>): void delete(callback: AsyncCallback\<void\>): void
Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result. Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result.
...@@ -979,7 +982,7 @@ Disables the cache and deletes the data in it. This API uses an asynchronous cal ...@@ -979,7 +982,7 @@ Disables the cache and deletes the data in it. This API uses an asynchronous cal
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -994,7 +997,7 @@ httpResponseCache.delete(err => { ...@@ -994,7 +997,7 @@ httpResponseCache.delete(err => {
``` ```
### delete<sup>9+</sup> ### delete<sup>9+</sup>
delete(): Promise\<void> delete(): Promise\<void\>
Disables the cache and deletes the data in it. This API uses a promise to return the result. Disables the cache and deletes the data in it. This API uses a promise to return the result.
...@@ -1004,7 +1007,7 @@ Disables the cache and deletes the data in it. This API uses a promise to return ...@@ -1004,7 +1007,7 @@ Disables the cache and deletes the data in it. This API uses a promise to return
| Type | Description | | Type | Description |
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Example** **Example**
......
# @ohos.net.connection (Network Connection Management) # @ohos.net.connection (Network Connection Management)
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. > 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 ## Modules to Import
...@@ -10,6 +10,40 @@ The **connection** module provides basic network management capabilities. You ca ...@@ -10,6 +10,40 @@ The **connection** module provides basic network management capabilities. You ca
```js ```js
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
``` ```
## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
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.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| 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.|
**Return value**
| Type | Description |
| ------------------------------- | -------------------- |
| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.|
**Example**
```js
// Default network
let netConnection = connection.createNetConnection()
// Cellular network
let netConnectionCellular = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
}
})
```
## connection.getDefaultNet ## connection.getDefaultNet
...@@ -25,14 +59,22 @@ Obtains the default active data network. This API uses an asynchronous callback ...@@ -25,14 +59,22 @@ Obtains the default active data network. This API uses an asynchronous callback
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet(function (error, netHandle) { connection.getDefaultNet(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(netHandle)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -52,17 +94,25 @@ Obtains the default active data network. This API uses a promise to return the r ...@@ -52,17 +94,25 @@ Obtains the default active data network. This API uses a promise to return the r
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<[NetHandle](#nethandle)> | Promise used to return the result.| | Promise\<[NetHandle](#nethandle)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (data) {
console.log(JSON.stringify(netHandle)) console.log(JSON.stringify(data))
}) })
``` ```
## connection.getDefaultNetSync<sup>9+</sup> ## connection.getDefaultNetSync<sup>9+</sup>
getDefaultNetSync(): NetHandle; getDefaultNetSync(): NetHandle
Obtains the default active data network in synchronous mode. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. 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 ...@@ -76,59 +126,321 @@ Obtains the default active data network in synchronous mode. You can use [getNet
| --------- | ---------------------------------- | | --------- | ---------------------------------- |
| NetHandle | Handle of the default active data network.| | NetHandle | Handle of the default active data network.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
let netHandle = connection.getDefaultNetSync(); let netHandle = connection.getDefaultNetSync();
``` ```
## connection.getGlobalHttpProxy<sup>10+</sup>
## connection.hasDefaultNet getGlobalHttpProxy(callback: AsyncCallback\<HttpProxy>): void
hasDefaultNet(callback: AsyncCallback\<boolean>): void 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. **System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| 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.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<[HttpProxy](#httpproxy)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getGlobalHttpProxy().then((data) => {
console.info(JSON.stringify(data));
}).catch(error => {
console.info(JSON.stringify(error));
})
```
## connection.setGlobalHttpProxy<sup>10+</sup>
setGlobalHttpProxy(httpProxy: HttpProxy, callback: AsyncCallback\<void>): void
Sets the global HTTP proxy configuration of the network. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | --------- | ------------------------------------------------------------ | ---- | ---------------- |
| 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.hasDefaultNet(function (error, has) { let exclusionStr="192.168,baidu.com"
let exclusionArray = exclusionStr.split(',');
let httpProxy = {
host: "192.168.xx.xxx",
port: 8080,
exclusionList: exclusionArray
}
connection.setGlobalHttpProxy(httpProxy, (error, data) => {
console.info(JSON.stringify(error));
console.info(JSON.stringify(data));
});
```
## connection.setGlobalHttpProxy<sup>10+</sup>
setGlobalHttpProxy(httpProxy: HttpProxy): Promise\<void>;
Sets the global HTTP proxy configuration of the network. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.|
**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
let exclusionStr="192.168,baidu.com"
let exclusionArray = exclusionStr.split(',');
let httpProxy = {
host: "192.168.xx.xxx",
port: 8080,
exclusionList: exclusionArray
}
connection.setGlobalHttpProxy(httpProxy).then((error, data) => {
console.info(JSON.stringify(data));
}).catch(error=>{
console.info(JSON.stringify(error));
})
```
## connection.getAppNet<sup>9+</sup>
getAppNet(callback: AsyncCallback\<NetHandle>): void
Obtains information about the network bound to an application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| 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(error))
console.log('has: ' + has) console.log(JSON.stringify(data))
}) })
``` ```
## connection.hasDefaultNet ## connection.getAppNet<sup>9+</sup>
hasDefaultNet(): Promise\<boolean> getAppNet(): Promise\<NetHandle>;
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 a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetHandle](#nethandle)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getAppNet().then((data) => {
console.info(JSON.stringify(data));
}).catch(error => {
console.info(JSON.stringify(error));
})
```
## connection.SetAppNet<sup>9+</sup>
setAppNet(netHandle: NetHandle, callback: AsyncCallback\<void>): void
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.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| 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.|
| 2100003 | System internal error. |
**Example**
```js
connection.getDefaultNet(function (error, netHandle) {
connection.setAppNet(netHandle, (error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
})
```
## connection.SetAppNet<sup>9+</sup>
setAppNet(netHandle: NetHandle): Promise\<void>;
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.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------- | ----------------------------------------------- | | ------------------------------------------- | ----------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates that the default data network is activated.| | 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** **Example**
```js ```js
connection.hasDefaultNet().then(function (has) { connection.getDefaultNet().then(function (netHandle) {
console.log('has: ' + has) connection.setAppNet(netHandle).then((error, data) => {
console.log(JSON.stringify(data))
}).catch(error => {
console.log(JSON.stringify(error))
})
}) })
``` ```
...@@ -136,7 +448,7 @@ connection.hasDefaultNet().then(function (has) { ...@@ -136,7 +448,7 @@ connection.hasDefaultNet().then(function (has) {
getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void
Obtains the list of all active data networks. This API uses an asynchronous callback to return the result. Obtains the list of all connected networks. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -146,23 +458,30 @@ Obtains the list of all active data networks. This API uses an asynchronous call ...@@ -146,23 +458,30 @@ Obtains the list of all active data networks. This API uses an asynchronous call
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Yes| Callback used to return the result.| | callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getAllNets(function (error, nets) { connection.getAllNets(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(nets)) console.log(JSON.stringify(data))
}); });
``` ```
## connection.getAllNets ## connection.getAllNets
getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt; getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt;
Obtains the list of all active data networks. This API uses a promise to return the result. Obtains the list of all connected networks. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -174,11 +493,19 @@ Obtains the list of all active data networks. This API uses a promise to return ...@@ -174,11 +493,19 @@ Obtains the list of all active data networks. This API uses a promise to return
| -------- | -------- | | -------- | -------- |
| Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Promise used to return the result.| | Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getAllNets().then(function (nets) { connection.getAllNets().then(function (data) {
console.log(JSON.stringify(nets)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -186,7 +513,7 @@ connection.getAllNets().then(function (nets) { ...@@ -186,7 +513,7 @@ connection.getAllNets().then(function (nets) {
getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void
Obtains connection properties of the network corresponding to the given network handle. This API uses an asynchronous callback to return the result. Obtains connection properties of the network corresponding to the **netHandle**. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -197,15 +524,25 @@ Obtains connection properties of the network corresponding to the given network ...@@ -197,15 +524,25 @@ Obtains connection properties of the network corresponding to the given network
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- | | --------- | ------------------------------------------------------------ | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getConnectionProperties(netHandle, function (error, info) { connection.getConnectionProperties(netHandle, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -214,7 +551,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -214,7 +551,7 @@ connection.getDefaultNet().then(function (netHandle) {
getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties> getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties>
Obtains connection properties of the network corresponding to **netHandle**. This API uses a promise to return the result. Obtains connection properties of the network corresponding to the **netHandle**. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -232,12 +569,22 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi ...@@ -232,12 +569,22 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi
| ------------------------------------------------------- | --------------------------------- | | ------------------------------------------------------- | --------------------------------- |
| Promise\<[ConnectionProperties](#connectionproperties)> | Promise used to return the result.| | Promise\<[ConnectionProperties](#connectionproperties)> | Promise used to return the result.|
**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** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getConnectionProperties(netHandle).then(function (info) { connection.getConnectionProperties(netHandle).then(function (data) {
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -246,7 +593,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -246,7 +593,7 @@ connection.getDefaultNet().then(function (netHandle) {
getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void
Obtains capability information of the network corresponding to **netHandle**. This API uses an asynchronous callback to return the result. Obtains capability information of the network corresponding to the **netHandle**. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -257,15 +604,25 @@ Obtains capability information of the network corresponding to **netHandle**. Th ...@@ -257,15 +604,25 @@ Obtains capability information of the network corresponding to **netHandle**. Th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | --------------------------------------------------- | ---- | ---------------- | | --------- | --------------------------------------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getNetCapabilities(netHandle, function (error, info) { connection.getNetCapabilities(netHandle, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -274,7 +631,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -274,7 +631,7 @@ connection.getDefaultNet().then(function (netHandle) {
getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities> getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities>
Obtains capability information of the network corresponding to **netHandle**. This API uses a promise to return the result. Obtains capability information of the network corresponding to the **netHandle**. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -292,12 +649,22 @@ Obtains capability information of the network corresponding to **netHandle**. Th ...@@ -292,12 +649,22 @@ Obtains capability information of the network corresponding to **netHandle**. Th
| --------------------------------------------- | --------------------------------- | | --------------------------------------------- | --------------------------------- |
| Promise\<[NetCapabilities](#netcapabilities)> | Promise used to return the result.| | Promise\<[NetCapabilities](#netcapabilities)> | Promise used to return the result.|
**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** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getNetCapabilities(netHandle).then(function (info) { connection.getNetCapabilities(netHandle).then(function (data) {
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -318,12 +685,20 @@ Checks whether the data traffic usage on the current network is metered. This AP ...@@ -318,12 +685,20 @@ Checks whether the data traffic usage on the current network is metered. This AP
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates the data traffic usage is metered.| | callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates the data traffic usage is metered.|
**Example**: **Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js ```js
connection.isDefaultNetMetered(function (error, has) { connection.isDefaultNetMetered(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log('has: ' + has) console.log('data: ' + data)
}) })
``` ```
...@@ -343,149 +718,162 @@ Checks whether the data traffic usage on the current network is metered. This AP ...@@ -343,149 +718,162 @@ Checks whether the data traffic usage on the current network is metered. This AP
| ----------------- | ----------------------------------------------- | | ----------------- | ----------------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates the data traffic usage is metered.| | Promise\<boolean> | Promise used to return the result. The value **true** indicates the data traffic usage is metered.|
**Example**: **Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js ```js
connection.isDefaultNetMetered().then(function (has) { connection.isDefaultNetMetered().then(function (data) {
console.log('has: ' + has) console.log('data: ' + data)
}) })
``` ```
## connection.reportNetConnected ## connection.hasDefaultNet
reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports connection of the data network. This API uses an asynchronous callback to return the result. hasDefaultNet(callback: AsyncCallback\<boolean>): void
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. 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.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name | Type | Mandatory| Description |
| -------- | -------- | -------- | -------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates the default data network is activated.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.hasDefaultNet(function (error, data) {
connection.reportNetConnected(netHandle, function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}); console.log('data: ' + data)
}); })
``` ```
## connection.reportNetConnected ## connection.hasDefaultNet
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports connection of the data network. This API uses a promise to return the result. hasDefaultNet(): Promise\<boolean>
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. 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.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Return value**
| Name| Type| Mandatory| Description| | Type | Description |
| -------- | -------- | -------- | -------- | | ----------------- | ----------------------------------------------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | Promise\<boolean> | Promise used to return the result. The value **true** indicates that the default data network is activated.|
**Return value** **Error codes**
| Type| Description| | ID| Error Message |
| -------- | -------- | | ------- | ----------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.hasDefaultNet().then(function (data) {
connection.reportNetConnected(netHandle).then(function () { console.log('data: ' + data)
console.log(`report success`) })
});
});
``` ```
## connection.enableAirplaneMode
## connection.reportNetDisconnected enableAirplaneMode(callback: AsyncCallback\<void>): void
reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports disconnection of the data network. This API uses an asynchronous callback to return the result. Enables the airplane mode. 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. **System API**: This is a system API.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | 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&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.enableAirplaneMode(function (error) {
connection.reportNetDisconnected(netHandle, function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}); })
});
``` ```
## connection.enableAirplaneMode
## connection.reportNetDisconnected enableAirplaneMode(): Promise\<void>
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports disconnection of the data network. This API uses a promise to return the result. Enables the airplane mode. 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. **System API**: This is a system API.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Return value**
| Name| Type| Mandatory| Description| | Type | Description |
| -------- | -------- | -------- | -------- | | ------------------------------------------- | ----------------------------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | Promise\<void> | Promise that returns no value.|
**Return value** **Error codes**
| Type| Description| | ID| Error Message |
| -------- | -------- | | ------- | ----------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.enableAirplaneMode().then(function (error) {
connection.reportNetDisconnected(netHandle).then(function () { console.log(JSON.stringify(error))
console.log(`report success`) })
});
});
``` ```
## connection.getAddressesByName ## connection.disableAirplaneMode
getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void disableAirplaneMode(callback: AsyncCallback\<void>): void
Resolves the host name by using the default network to obtain all IP addresses. This API uses an asynchronous callback to return the result. Disables the airplane mode. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
...@@ -493,178 +881,291 @@ Resolves the host name by using the default network to obtain all IP addresses. ...@@ -493,178 +881,291 @@ Resolves the host name by using the default network to obtain all IP addresses.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | ------------------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | 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.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
let host = "xxxx"; connection.disableAirplaneMode(function (error) {
connection.getAddressesByName(host, function (error, addresses) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(addresses))
}) })
``` ```
## connection.getAddressesByName ## connection.disableAirplaneMode
getAddressesByName(host: string): Promise\<Array\<NetAddress>>
Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result. disableAirplaneMode(): Promise\<void>
**Required permission**: ohos.permission.GET_NETWORK_INFO Disables the airplane mode. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core **System API**: This is a system API.
**Parameters** **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
| Name| Type | Mandatory| Description | **System capability**: SystemCapability.Communication.NetManager.Core
| ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.| | Promise\<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
let host = "xxxx"; connection.disableAirplaneMode().then(function (error) {
connection.getAddressesByName(host).then(function (addresses) { console.log(JSON.stringify(error))
console.log(JSON.stringify(addresses))
}) })
``` ```
## connection.enableAirplaneMode ## connection.reportNetConnected
enableAirplaneMode(callback: AsyncCallback\<void>): void reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Enables the airplane mode. This API uses an asynchronous callback to return the result. 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.
**System API**: This is a system API. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name| Type| Mandatory| Description|
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.enableAirplaneMode(function (error) { connection.getDefaultNet().then(function (netHandle) {
connection.reportNetConnected(netHandle, function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}) });
});
``` ```
## connection.enableAirplaneMode ## connection.reportNetConnected
enableAirplaneMode(): Promise\<void> reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
Enables the airplane mode. This API uses a promise to return the result. 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.
**System API**: This is a system API. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return value** **Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description | **Error codes**
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.| | 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** **Example**
```js ```js
connection.enableAirplaneMode().then(function (error) { connection.getDefaultNet().then(function (netHandle) {
console.log(JSON.stringify(error)) connection.reportNetConnected(netHandle).then(function () {
}) console.log(`report success`)
});
});
``` ```
## connection.disableAirplaneMode ## connection.reportNetDisconnected
disableAirplaneMode(callback: AsyncCallback\<void>): void reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Disables the airplane mode. This API uses an asynchronous callback to return the result. 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.
**System API**: This is a system API. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name| Type| Mandatory| Description|
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.disableAirplaneMode(function (error) { connection.getDefaultNet().then(function (netHandle) {
connection.reportNetDisconnected(netHandle, function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}) });
});
```
## connection.reportNetDisconnected
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | 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
connection.getDefaultNet().then(function (netHandle) {
connection.reportNetDisconnected(netHandle).then(function () {
console.log(`report success`)
});
});
``` ```
## connection.disableAirplaneMode ## connection.getAddressesByName
disableAirplaneMode(): Promise\<void> getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void
Disables the airplane mode. This API uses a promise to return the result. Resolves the host name by using the default network to obtain all IP addresses. This API uses an asynchronous callback to return the result.
**System API**: This is a system API. **Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Return value** **Parameters**
| Type | Description | | Name | Type | Mandatory| Description |
| ------------------------------------------- | ----------------------------- | | -------- | ------------------------------------------------- | ---- | ------------------ |
| Promise\<void> | Promise that returns no value.| | 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.disableAirplaneMode().then(function (error) { let host = "xxxx";
connection.getAddressesByName(host, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
}) })
``` ```
## connection.createNetConnection ## connection.getAddressesByName
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection getAddressesByName(host: string): Promise\<Array\<NetAddress>>
Obtains the handle of the network specified by **netSpecifier**. Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------ |
| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. | | host | string | Yes | Host name to resolve.|
| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------- | -------------------- | | ------------------------------------------- | ----------------------------- |
| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.| | Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.|
**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** **Example**
```js ```js
// Default network let host = "xxxx";
let netConnection = connection.createNetConnection() connection.getAddressesByName(host).then(function (data) {
console.log(JSON.stringify(data))
// Cellular network
let netConnectionCellular = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
}
}) })
``` ```
...@@ -672,73 +1173,108 @@ let netConnectionCellular = connection.createNetConnection({ ...@@ -672,73 +1173,108 @@ let netConnectionCellular = connection.createNetConnection({
Represents the network connection handle. Represents the network connection handle.
### on('netAvailable') ### register
on(type: 'netAvailable', callback: Callback\<NetHandle>): void register(callback: AsyncCallback\<void>): void
Registers a listener for **netAvailable** events. Registers a listener for network status changes.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | | -------- | -------------------- | ---- | ---------- |
| type | string | Yes | Event type. The value is fixed at **netAvailable**.<br>**netAvailable**: event indicating that the data network is available.| | 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.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
| 2101008 | The callback is not exists. |
| 2101022 | The number of requests exceeded the maximum. |
**Example** **Example**
```js ```js
netConnection.on('netAvailable', function (data) { netConnection.register(function (error) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(error))
}) })
``` ```
### on('netCapabilitiesChange') ### unregister
on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void unregister(callback: AsyncCallback\<void>): void
Registers a listener for **netCapabilitiesChange** events. Unregisters the listener for network status changes.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | -------------------- | ---- | ---------- |
| type | string | Yes | Event type. The value is fixed at **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that network capabilities have changed.| | 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.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
| 2101007 | The same callback exists. |
**Example** **Example**
```js ```js
netConnection.on('netCapabilitiesChange', function (data) { netConnection.unregister(function (error) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(error))
}) })
``` ```
### on('netConnectionPropertiesChange') ### on('netAvailable')
on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void on(type: 'netAvailable', callback: Callback\<NetHandle>): void
Registers a listener for **netConnectionPropertiesChange** events. Registers a listener for **netAvailable** events.
**Model restriction**: Before you call this API, make sure that you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| | type | string | Yes | Event type. The value is fixed to **netAvailable**.<br>**netAvailable**: event indicating that the data network is available.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the result. | | callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle.|
**Example** **Example**
```js ```js
netConnection.on('netConnectionPropertiesChange', function (data) { // Create a NetConnection object.
let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netAvailable events. Event notifications can be received only after register is called.
netCon.on('netAvailable', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### on('netBlockStatusChange') ### on('netBlockStatusChange')
...@@ -747,112 +1283,191 @@ on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, b ...@@ -747,112 +1283,191 @@ on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, b
Registers a listener for **netBlockStatusChange** 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.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.| | type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.|
| callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | Yes | Callback used to return the result. | | callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | Yes | Callback used to return the network handle (**netHandle**) and network status (**blocked**).|
**Example** **Example**
```js ```js
netConnection.on('netBlockStatusChange', function (data) { // Create a NetConnection object.
let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netBlockStatusChange events. Event notifications can be received only after register is called.
netCon.on('netBlockStatusChange', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### on('netLost') ### on('netCapabilitiesChange')
on(type: 'netLost', callback: Callback\<NetHandle>): void on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void
Registers a listener for **netLost** 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.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.| | 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)> | Yes | Callback used to return the result. | | callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
**Example** **Example**
```js ```js
let netConnection1 = connection.createNetConnection() // Create a NetConnection object.
netConnection1.on('netLost', function (data) { let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netCapabilitiesChange events. Event notifications can be received only after register is called.
netCon.on('netCapabilitiesChange', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### on('netUnavailable') ### on('netConnectionPropertiesChange')
on(type: 'netUnavailable', callback: Callback\<void>): void on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void
Registers a listener for **netUnavailable** 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.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.| | type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback\<void> | Yes | Callback used to return the result. | | callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
**Example** **Example**
```js ```js
netConnection.on('netUnavailable', function (data) { // Create a NetConnection object.
let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netConnectionPropertiesChange events. Event notifications can be received only after register is called.
netCon.on('netConnectionPropertiesChange', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### register ### on('netLost')
register(callback: AsyncCallback\<void>): void on(type: 'netLost', callback: Callback\<NetHandle>): void
Registers a listener for network status changes. Registers a listener for **netLost** events.
**Required permission**: ohos.permission.GET_NETWORK_INFO **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.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<void> | 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**).|
**Example** **Example**
```js ```js
netConnection.register(function (error) { // Create a NetConnection object.
let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netLost events. Event notifications can be received only after register is called.
netCon.on('netLost', function (data) {
console.log(JSON.stringify(data))
})
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}) })
``` ```
### unregister ### on('netUnavailable')
unregister(callback: AsyncCallback\<void>): void on(type: 'netUnavailable', callback: Callback\<void>): void
Unregisters the listener for network status changes. 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.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- | | -------- | --------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| | type | string | Yes | Event type. The value is fixed to **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.|
| callback | Callback\<void> | Yes | Callback used to return the result, which is empty.|
**Example** **Example**
```js ```js
netConnection.unregister(function (error) { // Create a NetConnection object.
let netCon = connection.createNetConnection()
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// Subscribe to netUnavailable events. Event notifications can be received only after register is called.
netCon.on('netUnavailable', function (data) {
console.log(JSON.stringify(data))
})
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}) })
``` ```
...@@ -861,24 +1476,22 @@ netConnection.unregister(function (error) { ...@@ -861,24 +1476,22 @@ netConnection.unregister(function (error) {
Defines the handle of the data network. Defines the handle of the data network.
Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** object. Before invoking **NetHandle** APIs, call **getNetHandle** to obtain a **NetHandle** object.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
### Parameters ### Attributes
| Name| Type | Description | | Name | Type | Mandatory| Description |
| ------ | ------ | ------------------------- | | ------ | ------ | --- |------------------------- |
| netId | number | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.| | netId | number | Yes | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.|
### bindSocket<sup>9+</sup> ### bindSocket<sup>9+</sup>
bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void; bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void
Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result. Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
...@@ -886,24 +1499,33 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -886,24 +1499,33 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------- | ------------------------ | ---- | -------------------------------| | ----------- | ------------------------ | ---- | -------------------------------|
| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.| | 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
import socket from "@ohos.net.socket"; import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{ connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
let socketType = "TCPSocket"; let socketType = "TCPSocket";
if (socketType == "TCPSocket") { if (socketType == "TCPSocket") {
tcp.bind({ tcp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
netHandle.bindSocket(tcp, (error, data)=>{ netHandle.bindSocket(tcp, (error, data) => {
if (error) { if (error) {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
} else { } else {
...@@ -913,19 +1535,19 @@ connection.getDefaultNet().then((netHandle)=>{ ...@@ -913,19 +1535,19 @@ connection.getDefaultNet().then((netHandle)=>{
}) })
} else { } else {
let callback = value => { let callback = value => {
console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
} }
udp.on('message', callback); udp.on('message', callback);
udp.bind({ udp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); });
netHandle.bindSocket(udp,(error, data)=>{ netHandle.bindSocket(udp, (error, data) => {
if (error) { if (error) {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
} else { } else {
...@@ -937,14 +1559,12 @@ connection.getDefaultNet().then((netHandle)=>{ ...@@ -937,14 +1559,12 @@ connection.getDefaultNet().then((netHandle)=>{
}) })
``` ```
### bindSocket ### bindSocket<sup>9+</sup>
bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>; bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>;
Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result. Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
...@@ -959,56 +1579,60 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -959,56 +1579,60 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
| -------------- | ---------------------- | | -------------- | ---------------------- |
| Promise\<void> | Promise that returns no value.| | Promise\<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
import socket from "@ohos.net.socket"; import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{ connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
let socketType = "TCPSocket"; let socketType = "TCPSocket";
if (socketType == "TCPSocket") { if (socketType == "TCPSocket") {
tcp.bind({ tcp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
netHandle.bindSocket(tcp).then((err, data) => { netHandle.bindSocket(tcp).then((data) => {
if (err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
} }).catch(error => {
console.log(JSON.stringify(error));
}) })
}) })
} else { } else {
let callback = value => { let callback = value => {
console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
} }
udp.on('message', callback); udp.on('message', callback);
udp.bind({ udp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
netHandle.bindSocket(udp).then((err, data) => { netHandle.bindSocket(udp).then((data) => {
if (err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
} }).catch(error => {
console.log(JSON.stringify(error));
}) })
}) })
} }
}) })
``` ```
### getAddressesByName ### getAddressesByName
getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void
...@@ -1023,17 +1647,27 @@ Resolves the host name by using the corresponding network to obtain all IP addre ...@@ -1023,17 +1647,27 @@ Resolves the host name by using the corresponding network to obtain all IP addre
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | ------------------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. | | 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressesByName(host, function (error, addresses) { netHandle.getAddressesByName(host, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(addresses)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -1052,7 +1686,7 @@ Resolves the host name by using the corresponding network to obtain all IP addre ...@@ -1052,7 +1686,7 @@ Resolves the host name by using the corresponding network to obtain all IP addre
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ | | ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to resolve.|
**Return value** **Return value**
...@@ -1060,13 +1694,23 @@ Resolves the host name by using the corresponding network to obtain all IP addre ...@@ -1060,13 +1694,23 @@ Resolves the host name by using the corresponding network to obtain all IP addre
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.| | Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.|
**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** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressesByName(host).then(function (addresses) { netHandle.getAddressesByName(host).then(function (data) {
console.log(JSON.stringify(addresses)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -1085,17 +1729,27 @@ Resolves the host name by using the corresponding network to obtain the first IP ...@@ -1085,17 +1729,27 @@ Resolves the host name by using the corresponding network to obtain the first IP
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------ | | -------- | ----------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. | | 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.|
| 2100003 | System internal error. |
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressByName(host, function (error, address) { netHandle.getAddressByName(host, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(address)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -1114,7 +1768,7 @@ Resolves the host name by using the corresponding network to obtain the first IP ...@@ -1114,7 +1768,7 @@ Resolves the host name by using the corresponding network to obtain the first IP
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ | | ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to resolve.|
**Return value** **Return value**
...@@ -1122,66 +1776,88 @@ Resolves the host name by using the corresponding network to obtain the first IP ...@@ -1122,66 +1776,88 @@ Resolves the host name by using the corresponding network to obtain the first IP
| ----------------------------------- | ------------------------------- | | ----------------------------------- | ------------------------------- |
| Promise\<[NetAddress](#netaddress)> | Promise used to return the result.| | Promise\<[NetAddress](#netaddress)> | Promise used to return the result.|
**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** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressByName(host).then(function (address) { netHandle.getAddressByName(host).then(function (data) {
console.log(JSON.stringify(address)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
## NetSpecifier ## NetCap
Provides an instance that bears data network capabilities. Defines the network capability.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Value | Description |
| -------- | ------- | --------- | ----------- | | ------------------------ | ---- | ---------------------- |
| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | | NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.|
| 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_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.|
## NetCapabilities ## NetBearType
Defines the network capability set. Enumerates network types.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Value | Description |
| -------- | ------- | --------- | ----------- | | --------------- | ---- | ----------- |
| linkUpBandwidthKbps | number | No | Uplink (from the device to the network) bandwidth.| | BEARER_CELLULAR | 0 | Cellular network. |
| linkDownBandwidthKbps | number | No | Downlink (from the network to the device) bandwidth.| | BEARER_WIFI | 1 | Wi-Fi network.|
| networkCap | Array<[NetCap](#netcap)> | No | Network capability. | | BEARER_ETHERNET | 3 | Ethernet network.|
| bearerTypes | Array<[NetBearType](#netbeartype)> | Yes | Network type. |
## NetCap ## HttpProxy<sup>10+</sup>
Defines the network capability. Defines the global HTTP proxy configuration of the network.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description | | Name | Type | Mandatory| Description |
| ------------------------ | ---- | ---------------------- | | ------ | ------ | --- |------------------------- |
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.| | host | string | No | Host name of the proxy server.|
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.| | port | number | No | Host port.|
| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.| | exclusionList | Array<string> | No | List of hosts that do not use the proxy server.|
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).|
| NET_CAPABILITY_VALIDATED | 16 | The network is available. |
## NetBearType ## NetSpecifier
Defines the network type. Provides an instance that bears data network capabilities.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description | | Name | Type | Mandatory | Description |
| --------------- | ---- | ----------- | | ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| BEARER_CELLULAR | 0 | Cellular network | | netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. |
| BEARER_WIFI | 1 | Wi-Fi 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).|
| BEARER_ETHERNET | 3 | Ethernet network|
## NetCapabilities
Defines the network capability set.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory| Description |
| --------------------- | ---------------------------------- | --- | ------------------------ |
| linkUpBandwidthKbps | number | No| Uplink (from the device to the network) bandwidth. |
| linkDownBandwidthKbps | number | No| Downlink (from the network to the device) bandwidth. |
| networkCap | Array\<[NetCap](#netcap)> | No| Network capability. |
| bearerTypes | Array\<[NetBearType](#netbeartype)> | Yes| Network type. |
## ConnectionProperties ## ConnectionProperties
...@@ -1189,48 +1865,48 @@ Defines the network connection properties. ...@@ -1189,48 +1865,48 @@ Defines the network connection properties.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ------------- | ---------------------------------- | ----|---------------- |
| interfaceName | string | Yes | NIC card name. | | interfaceName | string | Yes|Network interface card (NIC) name. |
| domains | string | Yes | Domain. The default value is **""**.| | domains | string | Yes|Domain. The default value is **""**.|
| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes | Link information. | | linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes|Link information. |
| routes | Array\<[RouteInfo](#routeinfo)> | Yes | Route information. | | routes | Array\<[RouteInfo](#routeinfo)> | Yes|Route information. |
| dnses | Array\<[NetAddress](#netaddress)>; | Yes | Network address. For details, see [NetAddress](#netaddress).| | dnses | Array\<[NetAddress](#netaddress)> | Yes|Network address. For details, see [NetAddress](#netaddress).|
| mtu | number | Yes | Maximum transmission unit (MTU). | | mtu | number | Yes|Maximum transmission unit (MTU). |
## LinkAddress ## RouteInfo
Network link information. Defines network route information.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Type | Mandatory|Description |
| -------- | ------- | --------- | ----------- | | -------------- | --------------------------- | --- |---------------- |
| address | [NetAddress](#netaddress) | Yes | Link address. | | interface | string | Yes|NIC name. |
| prefixLength | number | Yes | Length of the link address prefix.| | destination | [LinkAddress](#linkaddress) | Yes|Destination address. |
| gateway | [NetAddress](#netaddress) | Yes|Gateway address. |
| hasGateway | boolean | Yes|Whether a gateway is present. |
| isDefaultRoute | boolean | Yes|Whether the route is the default route.|
## RouteInfo ## LinkAddress
Network route information. Defines network link information.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Type | Mandatory|Description |
| -------- | ------- | --------- | ----------- | | ------------ | ----------------------- |---- |-------------------- |
| interface | string | Yes | NIC card name. | | address | [NetAddress](#netaddress) | Yes| Link address. |
| destination | [LinkAddress](#linkaddress) | Yes | Destination IP address. | | prefixLength | number | Yes|Length of the link address prefix.|
| gateway | [NetAddress](#netaddress) | Yes | Gateway address. |
| hasGateway | boolean | Yes | Whether a gateway is present. |
| isDefaultRoute | boolean | Yes | Whether the route is the default route.|
## NetAddress ## NetAddress
Defines the network address. Defines a network address.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ------- | ------ | -- |------------------------------ |
| address | string | Yes | Network address. | | address | string | Yes|Network address. |
| family | number | Yes | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| | family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.|
| port | number | No | Port number. The value ranges from **0** to **65535**. | | port | number | No|Port number. The value ranges from **0** to **65535**. |
...@@ -420,44 +420,44 @@ Enumerates mouse pointer styles. ...@@ -420,44 +420,44 @@ Enumerates mouse pointer styles.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer **System capability**: SystemCapability.MultimodalInput.Input.Pointer
| Name | Value | Description | | Name | Value | Description |Legend|
| -------------------------------- | ---- | ------ | | -------------------------------- | ---- | ------ |------ |
| DEFAULT | 0 | Default | | DEFAULT | 0 | Default |![Default.png](./figures/Default.png)|
| EAST | 1 | East arrow | | EAST | 1 | East arrow |![East.png](./figures/East.png)|
| WEST | 2 | West arrow | | WEST | 2 | West arrow |![West.png](./figures/West.png)|
| SOUTH | 3 | South arrow | | SOUTH | 3 | South arrow |![South.png](./figures/South.png)|
| NORTH | 4 | North arrow | | NORTH | 4 | North arrow |![North.png](./figures/North.png)|
| WEST_EAST | 5 | West-east arrow | | WEST_EAST | 5 | West-east arrow |![West_East.png](./figures/West_East.png)|
| NORTH_SOUTH | 6 | North-south arrow | | NORTH_SOUTH | 6 | North-south arrow |![North_South.png](./figures/North_South.png)|
| NORTH_EAST | 7 | North-east arrow | | NORTH_EAST | 7 | North-east arrow |![North_East.png](./figures/North_East.png)|
| NORTH_WEST | 8 | North-west arrow | | NORTH_WEST | 8 | North-west arrow |![North_West.png](./figures/North_West.png)|
| SOUTH_EAST | 9 | South-east arrow | | SOUTH_EAST | 9 | South-east arrow |![South_East.png](./figures/South_East.png)|
| SOUTH_WEST | 10 | South-west arrow | | SOUTH_WEST | 10 | South-west arrow |![South_West.png](./figures/South_West.png)|
| NORTH_EAST_SOUTH_WEST | 11 | North-east and south-west adjustment| | NORTH_EAST_SOUTH_WEST | 11 | North-east and south-west adjustment|![North_East_South_West.png](./figures/North_East_South_West.png)|
| NORTH_WEST_SOUTH_EAST | 12 | North-west and south-east adjustment| | NORTH_WEST_SOUTH_EAST | 12 | North-west and south-east adjustment|![North_West_South_East.png](./figures/North_West_South_East.png)|
| CROSS | 13 | Cross (accurate selection) | | CROSS | 13 | Cross (accurate selection) |![Cross.png](./figures/Cross.png)|
| CURSOR_COPY | 14 | Copy cursor | | CURSOR_COPY | 14 | Copy cursor |![Copy.png](./figures/Copy.png)|
| CURSOR_FORBID | 15 | Forbid cursor | | CURSOR_FORBID | 15 | Forbid cursor |![Forbid.png](./figures/Forbid.png)|
| COLOR_SUCKER | 16 | Sucker | | COLOR_SUCKER | 16 | Sucker |![Colorsucker.png](./figures/Colorsucker.png)|
| HAND_GRABBING | 17 | Grabbing hand | | HAND_GRABBING | 17 | Grabbing hand |![Hand_Grabbing.png](./figures/Hand_Grabbing.png)|
| HAND_OPEN | 18 | Opening hand | | HAND_OPEN | 18 | Opening hand |![Hand_Open.png](./figures/Hand_Open.png)|
| HAND_POINTING | 19 | Hand-shaped pointer | | HAND_POINTING | 19 | Hand-shaped pointer |![Hand_Poniting.png](./figures/Hand_Pointing.png)|
| HELP | 20 | Help | | HELP | 20 | Help |![Help.png](./figures/Help.png)|
| MOVE | 21 | Move | | MOVE | 21 | Move |![Move.png](./figures/Move.png)|
| RESIZE_LEFT_RIGHT | 22 | Left and right resizing| | RESIZE_LEFT_RIGHT | 22 | Left and right resizing|![Resize_Left_Right.png](./figures/Resize_Left_Right.png)|
| RESIZE_UP_DOWN | 23 | Up and down resizing| | RESIZE_UP_DOWN | 23 | Up and down resizing|![Resize_Up_Down.png](./figures/Resize_Up_Down.png)|
| SCREENSHOT_CHOOSE | 24 | Screenshot crosshair| | SCREENSHOT_CHOOSE | 24 | Screenshot crosshair|![Screenshot_Cross.png](./figures/Screenshot_Cross.png)|
| SCREENSHOT_CURSOR | 25 | Screenshot cursor | | SCREENSHOT_CURSOR | 25 | Screenshot cursor |![Screenshot_Cursor.png](./figures/Screenshot_Cursor.png)|
| TEXT_CURSOR | 26 | Text cursor | | TEXT_CURSOR | 26 | Text cursor |![Text_Cursor.png](./figures/Text_Cursor.png)|
| ZOOM_IN | 27 | Zoom in | | ZOOM_IN | 27 | Zoom in |![Zoom_In.png](./figures/Zoom_In.png)|
| ZOOM_OUT | 28 | Zoom out | | ZOOM_OUT | 28 | Zoom out |![Zoom_Out.png](./figures/Zoom_Out.png)|
| MIDDLE_BTN_EAST | 29 | Scrolling east | | MIDDLE_BTN_EAST | 29 | Scrolling east |![MID_Btn_East.png](./figures/MID_Btn_East.png)|
| MIDDLE_BTN_WEST | 30 | Scrolling west | | MIDDLE_BTN_WEST | 30 | Scrolling west |![MID_Btn_West.png](./figures/MID_Btn_West.png)|
| MIDDLE_BTN_SOUTH | 31 | Scrolling south | | MIDDLE_BTN_SOUTH | 31 | Scrolling south | ![MID_Btn_South.png](./figures/MID_Btn_South.png) |
| MIDDLE_BTN_NORTH | 32 | Scrolling north | | MIDDLE_BTN_NORTH | 32 | Scrolling north |![MID_Btn_North.png](./figures/MID_Btn_North.png)|
| MIDDLE_BTN_NORTH_SOUTH | 33 | Scrolling north-south | | MIDDLE_BTN_NORTH_SOUTH | 33 | Scrolling north-south |![MID_Btn_North_South.png](./figures/MID_Btn_North_South.png)|
| MIDDLE_BTN_NORTH_EAST | 34 | Scrolling north-east | | MIDDLE_BTN_NORTH_EAST | 34 | Scrolling north-east |![MID_Btn_North_East.png](./figures/MID_Btn_North_East.png)|
| MIDDLE_BTN_NORTH_WEST | 35 | Scrolling north-west | | MIDDLE_BTN_NORTH_WEST | 35 | Scrolling north-west |![MID_Btn_North_West.png](./figures/MID_Btn_North_West.png)|
| MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east | | MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east |![MID_Btn_South_East.png](./figures/MID_Btn_South_East.png)|
| MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west | | MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west |![MID_Btn_South_West.png](./figures/MID_Btn_South_West.png)|
| MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions| | MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions|![MID_Btn_North_South_West_East.png](./figures/MID_Btn_North_South_West_East.png)|
# # @ohos.net.socket (Socket Connection) # # @ohos.net.socket (Socket Connection)
The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSocket, and TLSSocket connections.
> **NOTE** > **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. > 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.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册