未验证 提交 87d4fdd5 编写于 作者: O openharmony_ci 提交者: Gitee

!16259 翻译已完成14756+15002+14956+15101

Merge pull request !16259 from shawn_he/14756-b
......@@ -67,7 +67,7 @@ httpRequest.request(
## 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.
......@@ -77,7 +77,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req
| 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**
......@@ -88,14 +88,17 @@ let httpRequest = http.createHttp();
## 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\(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.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -140,10 +143,13 @@ httpRequest.request("EXAMPLE_URL", (err, data) => {
### 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.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -223,10 +229,13 @@ httpRequest.request("EXAMPLE_URL",
### 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.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -309,7 +318,7 @@ promise.then((data) => {
### destroy
destroy\(\): void
destroy(): void
Destroys an HTTP request.
......@@ -323,7 +332,7 @@ httpRequest.destroy();
### 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.
......@@ -359,7 +368,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
```js
httpRequest.request2("EXAMPLE_URL", (err) => {
if (!err) {
console.info(request2 OK!);
console.info("request2 OK!");
} else {
console.info("request2 ERROR : err = " + JSON.stringify(err));
}
......@@ -368,9 +377,9 @@ httpRequest.request2("EXAMPLE_URL", (err) => {
### 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
......@@ -437,7 +446,7 @@ httpRequest.request2("EXAMPLE_URL",
connectTimeout: 60000
}, (err) => {
if (!err) {
console.info(request2 OK!);
console.info("request2 OK!");
} else {
console.info("request2 ERROR : err = " + JSON.stringify(err));
}
......@@ -445,7 +454,7 @@ httpRequest.request2("EXAMPLE_URL",
```
### 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.
......@@ -518,20 +527,20 @@ let promise = httpRequest.request("EXAMPLE_URL", {
}
});
promise.then(() => {
console.info(request2 OK!);
console.info("request2 OK!");
}).catch((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.
>**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
......@@ -545,24 +554,20 @@ Registers an observer for HTTP Response Header events.
**Example**
```js
httpRequest.on('headerReceive', (err, data) => {
if (!err) {
console.info('header: ' + JSON.stringify(data));
} else {
console.info('error:' + JSON.stringify(err));
}
httpRequest.on('headerReceive', (data) => {
console.info('error:' + JSON.stringify(data));
});
```
### 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.
>**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.
......@@ -581,9 +586,9 @@ Unregisters the observer for HTTP Response Header events.
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.
......@@ -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.
......@@ -628,9 +633,9 @@ Unregisters the observer for HTTP Response Header events.
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.
......@@ -650,9 +655,9 @@ httpRequest.once('headersReceive', (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.
......@@ -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.
......@@ -697,9 +702,9 @@ Unregisters the observer for events indicating receiving of HTTP streaming respo
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.
......@@ -720,7 +725,7 @@ httpRequest.on('dataReceive', () => {
});
```
### off\('dataEnd'\)<sup>10+</sup>
### off('dataEnd')<sup>10+</sup>
off(type: 'dataEnd', callback?: Callback\<void\>): void
......@@ -744,9 +749,9 @@ Unregisters the observer for events indicating completion of receiving HTTP stre
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.
......@@ -757,19 +762,17 @@ Registers an observer for events indicating progress of receiving HTTP streaming
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | --------------------------------- |
| 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**
```js
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
......@@ -915,11 +918,11 @@ let httpResponseCache = http.createHttpResponseCache();
## 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(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.
......@@ -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 |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example**
......@@ -945,7 +948,7 @@ httpResponseCache.flush(err => {
### 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.
......@@ -955,7 +958,7 @@ Flushes data in the cache to the file system so that the cached data can be acce
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void>> | Promise used to return the result.|
| Promise\<void\> | Promise used to return the result.|
**Example**
......@@ -969,7 +972,7 @@ httpResponseCache.flush().then(() => {
### 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.
......@@ -979,7 +982,7 @@ Disables the cache and deletes the data in it. This API uses an asynchronous cal
| 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**
......@@ -994,7 +997,7 @@ httpResponseCache.delete(err => {
```
### 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.
......@@ -1004,7 +1007,7 @@ Disables the cache and deletes the data in it. This API uses a promise to return
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void\> | Promise used to return the result.|
**Example**
......@@ -1023,7 +1026,7 @@ Enumerates HTTP data types.
**System capability**: SystemCapability.Communication.NetStack
| Name| Value| Description |
| ------------------ | -- | ----------- |
| ------------------ | -- | ----------- |
| STRING | 0 | String type.|
| OBJECT | 1 | Object type. |
| ARRAY_BUFFER | 2 | Binary array type.|
......
# @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.
## Modules to Import
......@@ -10,6 +10,40 @@ The **connection** module provides basic network management capabilities. You ca
```js
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
......@@ -25,14 +59,22 @@ Obtains the default active data network. This API uses an asynchronous callback
| 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**
```js
connection.getDefaultNet(function (error, netHandle) {
connection.getDefaultNet(function (error, data) {
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
| --------------------------------- | ------------------------------------- |
| 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**
```js
connection.getDefaultNet().then(function (netHandle) {
console.log(JSON.stringify(netHandle))
connection.getDefaultNet().then(function (data) {
console.log(JSON.stringify(data))
})
```
## 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.
......@@ -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.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
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
**Parameters**
| 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.|
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| 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**
```js
connection.hasDefaultNet(function (error, has) {
console.log(JSON.stringify(error))
console.log('has: ' + 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.hasDefaultNet
## connection.getAppNet<sup>9+</sup>
hasDefaultNet(): Promise\<boolean>
getAppNet(callback: AsyncCallback\<NetHandle>): void
Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any.
Obtains information about the network bound to an application. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**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(data))
})
```
## connection.getAppNet<sup>9+</sup>
getAppNet(): Promise\<NetHandle>;
Obtains information about the network bound to an application. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| ----------------- | ----------------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates that the default data network is activated.|
| 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
**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.hasDefaultNet().then(function (has) {
console.log('has: ' + has)
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**
| 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
connection.getDefaultNet().then(function (netHandle) {
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) {
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
......@@ -146,23 +458,30 @@ Obtains the list of all active data networks. This API uses an asynchronous call
| 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**
```js
connection.getAllNets(function (error, nets) {
connection.getAllNets(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(nets))
console.log(JSON.stringify(data))
});
```
## connection.getAllNets
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
......@@ -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.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getAllNets().then(function (nets) {
console.log(JSON.stringify(nets))
connection.getAllNets().then(function (data) {
console.log(JSON.stringify(data))
});
```
......@@ -186,7 +513,7 @@ connection.getAllNets().then(function (nets) {
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
......@@ -197,15 +524,25 @@ Obtains connection properties of the network corresponding to the given network
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| 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**
```js
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(info))
console.log(JSON.stringify(data))
})
})
```
......@@ -214,7 +551,7 @@ connection.getDefaultNet().then(function (netHandle) {
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
......@@ -232,12 +569,22 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi
| ------------------------------------------------------- | --------------------------------- |
| 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**
```js
connection.getDefaultNet().then(function (netHandle) {
connection.getConnectionProperties(netHandle).then(function (info) {
console.log(JSON.stringify(info))
connection.getConnectionProperties(netHandle).then(function (data) {
console.log(JSON.stringify(data))
})
})
```
......@@ -246,7 +593,7 @@ connection.getDefaultNet().then(function (netHandle) {
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
......@@ -257,15 +604,25 @@ Obtains capability information of the network corresponding to **netHandle**. Th
| Name | Type | Mandatory| Description |
| --------- | --------------------------------------------------- | ---- | ---------------- |
| 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**
```js
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(info))
console.log(JSON.stringify(data))
})
})
```
......@@ -274,7 +631,7 @@ connection.getDefaultNet().then(function (netHandle) {
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
......@@ -292,12 +649,22 @@ Obtains capability information of the network corresponding to **netHandle**. Th
| --------------------------------------------- | --------------------------------- |
| 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**
```js
connection.getDefaultNet().then(function (netHandle) {
connection.getNetCapabilities(netHandle).then(function (info) {
console.log(JSON.stringify(info))
connection.getNetCapabilities(netHandle).then(function (data) {
console.log(JSON.stringify(data))
})
})
```
......@@ -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.|
**Example**:
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.isDefaultNetMetered(function (error, has) {
connection.isDefaultNetMetered(function (error, data) {
console.log(JSON.stringify(error))
console.log('has: ' + has)
console.log('data: ' + data)
})
```
......@@ -343,11 +718,216 @@ 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.|
**Example**:
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.isDefaultNetMetered().then(function (data) {
console.log('data: ' + data)
})
```
## connection.hasDefaultNet
hasDefaultNet(callback: AsyncCallback\<boolean>): void
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.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates the default data network is activated.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.hasDefaultNet(function (error, data) {
console.log(JSON.stringify(error))
console.log('data: ' + data)
})
```
## connection.hasDefaultNet
hasDefaultNet(): Promise\<boolean>
Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| ----------------- | ----------------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates that the default data network is activated.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.isDefaultNetMetered().then(function (has) {
console.log('has: ' + has)
connection.hasDefaultNet().then(function (data) {
console.log('data: ' + data)
})
```
## connection.enableAirplaneMode
enableAirplaneMode(callback: AsyncCallback\<void>): void
Enables the airplane mode. 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
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.enableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.enableAirplaneMode
enableAirplaneMode(): Promise\<void>
Enables the airplane mode. 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
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.enableAirplaneMode().then(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode
disableAirplaneMode(callback: AsyncCallback\<void>): void
Disables the airplane mode. 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
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the airplane mode is disabled successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.disableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode
disableAirplaneMode(): Promise\<void>
Disables the airplane mode. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.disableAirplaneMode().then(function (error) {
console.log(JSON.stringify(error))
})
```
......@@ -355,9 +935,8 @@ connection.isDefaultNetMetered().then(function (has) {
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.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
......@@ -368,7 +947,17 @@ If this API is called, the application considers that the network connection sta
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| 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**
......@@ -384,9 +973,8 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports connection of the data network. This API uses a promise to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
......@@ -399,11 +987,20 @@ If this API is called, the application considers that the network connection sta
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&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
......@@ -414,14 +1011,12 @@ connection.getDefaultNet().then(function (netHandle) {
});
```
## connection.reportNetDisconnected
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.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
......@@ -432,7 +1027,17 @@ If this API is called, the application considers that the network connection sta
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| 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**
......@@ -444,14 +1049,12 @@ connection.getDefaultNet().then(function (netHandle) {
});
```
## connection.reportNetDisconnected
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports disconnection of the data network. This API uses a promise to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
......@@ -464,11 +1067,20 @@ If this API is called, the application considers that the network connection sta
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&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
......@@ -493,213 +1105,185 @@ Resolves the host name by using the default network to obtain all IP addresses.
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. |
**Example**
```js
let host = "xxxx";
connection.getAddressesByName(host, function (error, addresses) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(addresses))
})
```
## connection.getAddressesByName
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.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.|
**Example**
```js
let host = "xxxx";
connection.getAddressesByName(host).then(function (addresses) {
console.log(JSON.stringify(addresses))
})
```
## connection.enableAirplaneMode
enableAirplaneMode(callback: AsyncCallback\<void>): void
Enables the airplane mode. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
| host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **err** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.enableAirplaneMode(function (error) {
let host = "xxxx";
connection.getAddressesByName(host, function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## connection.enableAirplaneMode
## connection.getAddressesByName
enableAirplaneMode(): Promise\<void>
getAddressesByName(host: string): Promise\<Array\<NetAddress>>
Enables 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 a promise 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
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to resolve.|
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.|
| 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**
```js
connection.enableAirplaneMode().then(function (error) {
console.log(JSON.stringify(error))
let host = "xxxx";
connection.getAddressesByName(host).then(function (data) {
console.log(JSON.stringify(data))
})
```
## connection.disableAirplaneMode
disableAirplaneMode(callback: AsyncCallback\<void>): void
Disables the airplane mode. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
## NetConnection
**Parameters**
Represents the network connection handle.
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
### register
**Example**
register(callback: AsyncCallback\<void>): void
```js
connection.disableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
Registers a listener for network status changes.
## connection.disableAirplaneMode
**Required permission**: ohos.permission.GET_NETWORK_INFO
disableAirplaneMode(): Promise\<void>
**System capability**: SystemCapability.Communication.NetManager.Core
Disables the airplane mode. This API uses a promise to return the result.
**Parameters**
**System API**: This is a system API.
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| 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.|
**System capability**: SystemCapability.Communication.NetManager.Core
**Error codes**
**Return value**
| 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. |
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise that returns no value.|
**Example**
```js
connection.disableAirplaneMode().then(function (error) {
netConnection.register(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.createNetConnection
### unregister
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
unregister(callback: AsyncCallback\<void>): void
Obtains the handle of the network specified by **netSpecifier**.
Unregisters the listener for network status changes.
**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.|
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| 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.|
**Return value**
**Error codes**
| Type | Description |
| ------------------------------- | -------------------- |
| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.|
| ID| Error Message |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
| 2101007 | The same callback exists. |
**Example**
```js
// Default network
let netConnection = connection.createNetConnection()
// Cellular network
let netConnectionCellular = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
}
netConnection.unregister(function (error) {
console.log(JSON.stringify(error))
})
```
## NetConnection
Represents the network connection handle.
### on('netAvailable')
on(type: 'netAvailable', callback: Callback\<NetHandle>): void
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
**Parameters**
| 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 | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. |
| 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)> | Yes | Callback used to return the network handle.|
**Example**
```js
netConnection.on('netAvailable', 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))
})
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
```
### on('netCapabilitiesChange')
### on('netBlockStatusChange')
on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void
on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, blocked: boolean }&gt;): void
Registers a listener for **netCapabilitiesChange** events.
Registers a listener for **netBlockStatusChange** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -707,22 +1291,38 @@ Registers a listener for **netCapabilitiesChange** events.
| 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 | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.|
| callback | Callback&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**
```js
netConnection.on('netCapabilitiesChange', 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))
})
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
```
### on('netConnectionPropertiesChange')
### on('netCapabilitiesChange')
on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void
on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void
Registers a listener for **netConnectionPropertiesChange** events.
Registers a listener for **netCapabilitiesChange** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -730,22 +1330,38 @@ Registers a listener for **netConnectionPropertiesChange** events.
| 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.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that the network capabilities have changed.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
**Example**
```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 netCapabilitiesChange events. Event notifications can be received only after register is called.
netCon.on('netCapabilitiesChange', function (data) {
console.log(JSON.stringify(data))
})
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
```
### on('netBlockStatusChange')
### on('netConnectionPropertiesChange')
on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, blocked: boolean }&gt;): void
on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void
Registers a listener for **netBlockStatusChange** events.
Registers a listener for **netConnectionPropertiesChange** events.
**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -753,15 +1369,29 @@ Registers a listener for **netBlockStatusChange** events.
| 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.|
| callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
**Example**
```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 netConnectionPropertiesChange events. Event notifications can be received only after register is called.
netCon.on('netConnectionPropertiesChange', function (data) {
console.log(JSON.stringify(data))
})
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
```
### on('netLost')
......@@ -770,22 +1400,37 @@ on(type: 'netLost', callback: Callback\<NetHandle>): void
Registers a listener for **netLost** 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
**Parameters**
| 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.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle (**netHandle**).|
**Example**
```js
let netConnection1 = connection.createNetConnection()
netConnection1.on('netLost', 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 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))
})
```
### on('netUnavailable')
......@@ -794,65 +1439,35 @@ on(type: 'netUnavailable', callback: Callback\<void>): void
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
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.|
| callback | Callback\<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**
```js
netConnection.on('netUnavailable', function (data) {
console.log(JSON.stringify(data))
})
```
### register
register(callback: AsyncCallback\<void>): void
Registers a listener for network status changes.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
// Create a NetConnection object.
let netCon = connection.createNetConnection()
**Example**
```js
netConnection.register(function (error) {
// Call register to register a listener.
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
```
### unregister
unregister(callback: AsyncCallback\<void>): void
Unregisters the listener for network status changes.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
// Subscribe to netUnavailable events. Event notifications can be received only after register is called.
netCon.on('netUnavailable', function (data) {
console.log(JSON.stringify(data))
})
```js
netConnection.unregister(function (error) {
// Call unregister to unregister the listener.
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
```
......@@ -861,24 +1476,22 @@ netConnection.unregister(function (error) {
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
### Parameters
### Attributes
| Name| Type | Description |
| ------ | ------ | ------------------------- |
| netId | number | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.|
| Name | Type | Mandatory| Description |
| ------ | ------ | --- |------------------------- |
| 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(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.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
......@@ -886,24 +1499,33 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
| Name | Type | Mandatory| Description |
| ----------- | ------------------------ | ---- | -------------------------------|
| 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**
```js
import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{
connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance();
let socketType = "TCPSocket";
if (socketType == "TCPSocket") {
tcp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => {
if (err) {
address: '192.168.xx.xxx', port: 8080, family: 1
}, error => {
if (error) {
console.log('bind fail');
}
netHandle.bindSocket(tcp, (error, data)=>{
netHandle.bindSocket(tcp, (error, data) => {
if (error) {
console.log(JSON.stringify(error));
} else {
......@@ -913,19 +1535,19 @@ connection.getDefaultNet().then((netHandle)=>{
})
} else {
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.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => {
if (err) {
address: '192.168.xx.xxx', port: 8080, family: 1
}, error => {
if (error) {
console.log('bind fail');
}
udp.on('message', (data) => {
console.log(JSON.stringify(data))
});
netHandle.bindSocket(udp,(error, data)=>{
netHandle.bindSocket(udp, (error, data) => {
if (error) {
console.log(JSON.stringify(error));
} else {
......@@ -937,14 +1559,12 @@ connection.getDefaultNet().then((netHandle)=>{
})
```
### bindSocket
### bindSocket<sup>9+</sup>
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.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
......@@ -959,56 +1579,60 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
| -------------- | ---------------------- |
| 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**
```js
import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{
connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance();
let socketType = "TCPSocket";
if (socketType == "TCPSocket") {
tcp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => {
if (err) {
address: '192.168.xx.xxx', port: 8080, family: 1
}, error => {
if (error) {
console.log('bind fail');
}
netHandle.bindSocket(tcp).then((err, data) => {
if (err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(data));
}
netHandle.bindSocket(tcp).then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
})
})
} else {
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.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => {
if (err) {
address: '192.168.xx.xxx', port: 8080, family: 1
}, error => {
if (error) {
console.log('bind fail');
}
udp.on('message', (data) => {
console.log(JSON.stringify(data));
})
netHandle.bindSocket(udp).then((err, data) => {
if (err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(data));
}
netHandle.bindSocket(udp).then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
})
})
}
})
```
### getAddressesByName
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
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. |
| host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **err** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx";
netHandle.getAddressesByName(host, function (error, addresses) {
netHandle.getAddressesByName(host, function (error, data) {
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
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
| host | string | Yes | Host name to resolve.|
**Return value**
......@@ -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.|
**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) {
let host = "xxxx";
netHandle.getAddressesByName(host).then(function (addresses) {
console.log(JSON.stringify(addresses))
netHandle.getAddressesByName(host).then(function (data) {
console.log(JSON.stringify(data))
})
})
```
......@@ -1085,17 +1729,27 @@ Resolves the host name by using the corresponding network to obtain the first IP
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. |
| host | string | Yes | Host name to resolve.|
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the first IP address is obtained successfully, **err** is **undefined**, and **data** is the first obtained IP address. Otherwise, **err** is an error object. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx";
netHandle.getAddressByName(host, function (error, address) {
netHandle.getAddressByName(host, function (error, data) {
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
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
| host | string | Yes | Host name to resolve.|
**Return value**
......@@ -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.|
**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) {
let host = "xxxx";
netHandle.getAddressByName(host).then(function (address) {
console.log(JSON.stringify(address))
netHandle.getAddressByName(host).then(function (data) {
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
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. |
| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|
| Name | Value | Description |
| ------------------------ | ---- | ---------------------- |
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.|
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.|
| NET_CAPABILITY_INTERNET | 12 | The network has the Internet access capability, which is set by the network provider.|
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a virtual private network (VPN).|
| NET_CAPABILITY_VALIDATED | 16 | The Internet access capability of the network is successfully verified by the connection management module.|
## NetCapabilities
## NetBearType
Defines the network capability set.
Enumerates network types.
**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. |
| Name | Value | Description |
| --------------- | ---- | ----------- |
| BEARER_CELLULAR | 0 | Cellular network. |
| BEARER_WIFI | 1 | Wi-Fi network.|
| BEARER_ETHERNET | 3 | Ethernet network.|
## NetCap
## HttpProxy<sup>10+</sup>
Defines the network capability.
Defines the global HTTP proxy configuration of the network.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
| ------------------------ | ---- | ---------------------- |
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.|
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.|
| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.|
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).|
| NET_CAPABILITY_VALIDATED | 16 | The network is available. |
| Name | Type | Mandatory| Description |
| ------ | ------ | --- |------------------------- |
| host | string | No | Host name of the proxy server.|
| port | number | No | Host port.|
| exclusionList | Array<string> | No | List of hosts that do not use the proxy server.|
## NetBearType
## NetSpecifier
Defines the network type.
Provides an instance that bears data network capabilities.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
| --------------- | ---- | ----------- |
| BEARER_CELLULAR | 0 | Cellular network |
| BEARER_WIFI | 1 | Wi-Fi network|
| BEARER_ETHERNET | 3 | Ethernet network|
| Name | Type | Mandatory | Description |
| ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. |
| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|
## 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
......@@ -1189,48 +1865,48 @@ Defines the network connection properties.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| interfaceName | string | Yes | NIC card name. |
| domains | string | Yes | Domain. The default value is **""**.|
| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes | Link information. |
| routes | Array\<[RouteInfo](#routeinfo)> | Yes | Route information. |
| dnses | Array\<[NetAddress](#netaddress)>; | Yes | Network address. For details, see [NetAddress](#netaddress).|
| mtu | number | Yes | Maximum transmission unit (MTU). |
| Name | Type | Mandatory| Description |
| ------------- | ---------------------------------- | ----|---------------- |
| interfaceName | string | Yes|Network interface card (NIC) name. |
| domains | string | Yes|Domain. The default value is **""**.|
| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes|Link information. |
| routes | Array\<[RouteInfo](#routeinfo)> | Yes|Route information. |
| dnses | Array\<[NetAddress](#netaddress)> | Yes|Network address. For details, see [NetAddress](#netaddress).|
| mtu | number | Yes|Maximum transmission unit (MTU). |
## LinkAddress
## RouteInfo
Network link information.
Defines network route information.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| address | [NetAddress](#netaddress) | Yes | Link address. |
| prefixLength | number | Yes | Length of the link address prefix.|
| Name | Type | Mandatory|Description |
| -------------- | --------------------------- | --- |---------------- |
| interface | string | Yes|NIC name. |
| 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
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| interface | string | Yes | NIC card name. |
| destination | [LinkAddress](#linkaddress) | Yes | Destination IP 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.|
| Name | Type | Mandatory|Description |
| ------------ | ----------------------- |---- |-------------------- |
| address | [NetAddress](#netaddress) | Yes| Link address. |
| prefixLength | number | Yes|Length of the link address prefix.|
## NetAddress
Defines the network address.
Defines a network address.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| 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**.|
| port | number | No | Port number. The value ranges from **0** to **65535**. |
| Name | Type | Mandatory| Description |
| ------- | ------ | -- |------------------------------ |
| address | string | Yes|Network address. |
| family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.|
| port | number | No|Port number. The value ranges from **0** to **65535**. |
......@@ -420,44 +420,44 @@ Enumerates mouse pointer styles.
**System capability**: SystemCapability.MultimodalInput.Input.Pointer
| Name | Value | Description |
| -------------------------------- | ---- | ------ |
| DEFAULT | 0 | Default |
| EAST | 1 | East arrow |
| WEST | 2 | West arrow |
| SOUTH | 3 | South arrow |
| NORTH | 4 | North arrow |
| WEST_EAST | 5 | West-east arrow |
| NORTH_SOUTH | 6 | North-south arrow |
| NORTH_EAST | 7 | North-east arrow |
| NORTH_WEST | 8 | North-west arrow |
| SOUTH_EAST | 9 | South-east arrow |
| SOUTH_WEST | 10 | South-west arrow |
| NORTH_EAST_SOUTH_WEST | 11 | North-east and south-west adjustment|
| NORTH_WEST_SOUTH_EAST | 12 | North-west and south-east adjustment|
| CROSS | 13 | Cross (accurate selection) |
| CURSOR_COPY | 14 | Copy cursor |
| CURSOR_FORBID | 15 | Forbid cursor |
| COLOR_SUCKER | 16 | Sucker |
| HAND_GRABBING | 17 | Grabbing hand |
| HAND_OPEN | 18 | Opening hand |
| HAND_POINTING | 19 | Hand-shaped pointer |
| HELP | 20 | Help |
| MOVE | 21 | Move |
| RESIZE_LEFT_RIGHT | 22 | Left and right resizing|
| RESIZE_UP_DOWN | 23 | Up and down resizing|
| SCREENSHOT_CHOOSE | 24 | Screenshot crosshair|
| SCREENSHOT_CURSOR | 25 | Screenshot cursor |
| TEXT_CURSOR | 26 | Text cursor |
| ZOOM_IN | 27 | Zoom in |
| ZOOM_OUT | 28 | Zoom out |
| MIDDLE_BTN_EAST | 29 | Scrolling east |
| MIDDLE_BTN_WEST | 30 | Scrolling west |
| MIDDLE_BTN_SOUTH | 31 | Scrolling south |
| MIDDLE_BTN_NORTH | 32 | Scrolling north |
| MIDDLE_BTN_NORTH_SOUTH | 33 | Scrolling north-south |
| MIDDLE_BTN_NORTH_EAST | 34 | Scrolling north-east |
| MIDDLE_BTN_NORTH_WEST | 35 | Scrolling north-west |
| MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east |
| MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west |
| MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions|
| Name | Value | Description |Legend|
| -------------------------------- | ---- | ------ |------ |
| DEFAULT | 0 | Default |![Default.png](./figures/Default.png)|
| EAST | 1 | East arrow |![East.png](./figures/East.png)|
| WEST | 2 | West arrow |![West.png](./figures/West.png)|
| SOUTH | 3 | South arrow |![South.png](./figures/South.png)|
| NORTH | 4 | North arrow |![North.png](./figures/North.png)|
| WEST_EAST | 5 | West-east arrow |![West_East.png](./figures/West_East.png)|
| NORTH_SOUTH | 6 | North-south arrow |![North_South.png](./figures/North_South.png)|
| NORTH_EAST | 7 | North-east arrow |![North_East.png](./figures/North_East.png)|
| NORTH_WEST | 8 | North-west arrow |![North_West.png](./figures/North_West.png)|
| SOUTH_EAST | 9 | South-east arrow |![South_East.png](./figures/South_East.png)|
| 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.png](./figures/North_East_South_West.png)|
| 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.png](./figures/Cross.png)|
| CURSOR_COPY | 14 | Copy cursor |![Copy.png](./figures/Copy.png)|
| CURSOR_FORBID | 15 | Forbid cursor |![Forbid.png](./figures/Forbid.png)|
| COLOR_SUCKER | 16 | Sucker |![Colorsucker.png](./figures/Colorsucker.png)|
| HAND_GRABBING | 17 | Grabbing hand |![Hand_Grabbing.png](./figures/Hand_Grabbing.png)|
| HAND_OPEN | 18 | Opening hand |![Hand_Open.png](./figures/Hand_Open.png)|
| HAND_POINTING | 19 | Hand-shaped pointer |![Hand_Poniting.png](./figures/Hand_Pointing.png)|
| HELP | 20 | Help |![Help.png](./figures/Help.png)|
| MOVE | 21 | Move |![Move.png](./figures/Move.png)|
| 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.png](./figures/Resize_Up_Down.png)|
| SCREENSHOT_CHOOSE | 24 | Screenshot crosshair|![Screenshot_Cross.png](./figures/Screenshot_Cross.png)|
| SCREENSHOT_CURSOR | 25 | Screenshot cursor |![Screenshot_Cursor.png](./figures/Screenshot_Cursor.png)|
| TEXT_CURSOR | 26 | Text cursor |![Text_Cursor.png](./figures/Text_Cursor.png)|
| ZOOM_IN | 27 | Zoom in |![Zoom_In.png](./figures/Zoom_In.png)|
| ZOOM_OUT | 28 | Zoom out |![Zoom_Out.png](./figures/Zoom_Out.png)|
| MIDDLE_BTN_EAST | 29 | Scrolling east |![MID_Btn_East.png](./figures/MID_Btn_East.png)|
| MIDDLE_BTN_WEST | 30 | Scrolling west |![MID_Btn_West.png](./figures/MID_Btn_West.png)|
| MIDDLE_BTN_SOUTH | 31 | Scrolling south | ![MID_Btn_South.png](./figures/MID_Btn_South.png) |
| MIDDLE_BTN_NORTH | 32 | Scrolling north |![MID_Btn_North.png](./figures/MID_Btn_North.png)|
| 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 |![MID_Btn_North_East.png](./figures/MID_Btn_North_East.png)|
| 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 |![MID_Btn_South_East.png](./figures/MID_Btn_South_East.png)|
| 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|![MID_Btn_North_South_West_East.png](./figures/MID_Btn_North_South_West_East.png)|
# # @ohos.net.socket (Socket Connection)
The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSocket, and TLSSocket connections.
> **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.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册