提交 310fcd38 编写于 作者: Y Yangys

Update ErrorCode Monthly

Signed-off-by: NYangys <yangyousheng@huawei.com>
上级 db112bcc
...@@ -18,32 +18,41 @@ HTTP数据请求功能主要由http模块提供。 ...@@ -18,32 +18,41 @@ HTTP数据请求功能主要由http模块提供。
| ----------------------------------------- | ----------------------------------- | | ----------------------------------------- | ----------------------------------- |
| createHttp() | 创建一个http请求。 | | createHttp() | 创建一个http请求。 |
| request() | 根据URL地址,发起HTTP网络请求。 | | request() | 根据URL地址,发起HTTP网络请求。 |
| request2()<sup>10+</sup> | 根据URL地址,发起HTTP网络请求并返回流式响应|
| destroy() | 中断请求任务。 | | destroy() | 中断请求任务。 |
| on(type: 'headersReceive') | 订阅HTTP Response Header 事件。 | | on(type: 'headersReceive') | 订阅HTTP Response Header 事件。 |
| off(type: 'headersReceive') | 取消订阅HTTP Response Header 事件。 | | off(type: 'headersReceive') | 取消订阅HTTP Response Header 事件。 |
| once\('headersReceive'\)<sup>8+</sup> | 订阅HTTP Response Header 事件,但是只触发一次。|
| on\('dataReceive'\)<sup>10+</sup> | 订阅HTTP流式响应数据接收事件。 |
| off\('dataReceive'\)<sup>10+</sup> | 取消订阅HTTP流式响应数据接收事件。 |
| on\('dataEnd'\)<sup>10+</sup> | 订阅HTTP流式响应数据接收完毕事件。 |
| off\('dataEnd'\)<sup>10+</sup> | 取消订阅HTTP流式响应数据接收完毕事件。 |
| on\('dataProgress'\)<sup>10+</sup> | 订阅HTTP流式响应数据接收进度事件。 |
| off\('dataProgress'\)<sup>10+</sup> | 取消订阅HTTP流式响应数据接收进度事件。 |
## 开发步骤 ## 开发步骤
1. import需要的http模块。 1. 从@ohos.net.http.d.ts中导入http命名空间。
2. 创建一个HTTP请求,返回一个HttpRequest对象。 2. 调用createHttp()方法,创建一个HttpRequest对象。
3. (可选)订阅HTTP响应头。 3. 调用该对象的on()方法,订阅http响应头事件,此接口会比request请求先返回。可以根据业务需要订阅此消息。
4. 根据URL地址,发起HTTP网络请求。 4. 调用该对象的request()方法,传入http请求的url地址和可选参数,发起网络请求。
5. (可选)处理HTTP响应头和HTTP网络请求的返回结果。 5. 按照实际业务需要,解析返回结果。
6. 调用该对象的off()方法,取消订阅http响应头事件。
7. 当该请求使用完毕时,调用destroy()方法主动销毁。
```js ```js
// 引入包名
import http from '@ohos.net.http'; import http from '@ohos.net.http';
// 每一个httpRequest对应一个http请求任务,不可复用 // 每一个httpRequest对应一个HTTP请求任务,不可复用
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 用于订阅http响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+ // 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// 填写http请求的url地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
...@@ -55,19 +64,26 @@ httpRequest.request( ...@@ -55,19 +64,26 @@ httpRequest.request(
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
connectTimeout: 60000, // 可选,默认为60s expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
readTimeout: 60000, // 可选,默认为60s usingCache: true, // 可选,默认为true
priority: 1, // 可选,默认为1
connectTimeout: 60000, // 可选,默认为60000ms
readTimeout: 60000, // 可选,默认为60000ms
usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
// data.result为http响应内容,可根据业务需要进行解析 // data.result为HTTP响应内容,可根据业务需要进行解析
console.info('Result:' + data.result); console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + data.responseCode); console.info('code:' + JSON.stringify(data.responseCode));
// data.header为http响应头,可根据业务需要进行解析 // data.header为HTTP响应头,可根据业务需要进行解析
console.info('header:' + JSON.stringify(data.header)); console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else { } else {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
// 该请求不再使用,调用destroy方法主动销毁。 // 取消订阅HTTP响应头事件
httpRequest.off('headersReceive');
// 当该请求使用完毕时,调用destroy方法主动销毁。
httpRequest.destroy(); httpRequest.destroy();
} }
} }
...@@ -76,5 +92,5 @@ httpRequest.request( ...@@ -76,5 +92,5 @@ httpRequest.request(
## 相关实例 ## 相关实例
针对HTTP数据请求,有以下相关实例可供参考: 针对HTTP数据请求,有以下相关实例可供参考:
- [`Http:`数据请求(ArkTS)(API9))](https://gitee.com/openharmony/applications_app_samples/tree/monthly_20221018/Network/Http) - [`Http:`数据请求(ArkTS)(API9))](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [使用HTTP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH) - [使用HTTP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
\ No newline at end of file
...@@ -16,6 +16,7 @@ import http from '@ohos.net.http'; ...@@ -16,6 +16,7 @@ import http from '@ohos.net.http';
## 完整示例 ## 完整示例
```js ```js
// 引入包名
import http from '@ohos.net.http'; import http from '@ohos.net.http';
// 每一个httpRequest对应一个HTTP请求任务,不可复用 // 每一个httpRequest对应一个HTTP请求任务,不可复用
...@@ -44,16 +45,19 @@ httpRequest.request( ...@@ -44,16 +45,19 @@ httpRequest.request(
connectTimeout: 60000, // 可选,默认为60000ms connectTimeout: 60000, // 可选,默认为60000ms
readTimeout: 60000, // 可选,默认为60000ms readTimeout: 60000, // 可选,默认为60000ms
usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定 usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
// data.result为HTTP响应内容,可根据业务需要进行解析 // data.result为HTTP响应内容,可根据业务需要进行解析
console.info('Result:' + data.result); console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + data.responseCode); console.info('code:' + JSON.stringify(data.responseCode));
// data.header为HTTP响应头,可根据业务需要进行解析 // data.header为HTTP响应头,可根据业务需要进行解析
console.info('header:' + JSON.stringify(data.header)); console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else { } else {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
// 取消订阅HTTP响应头事件
httpRequest.off('headersReceive');
// 当该请求使用完毕时,调用destroy方法主动销毁。 // 当该请求使用完毕时,调用destroy方法主动销毁。
httpRequest.destroy(); httpRequest.destroy();
} }
...@@ -103,6 +107,22 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void ...@@ -103,6 +107,22 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void
| url | string | 是 | 发起网络请求的URL地址。 | | url | string | 是 | 发起网络请求的URL地址。 |
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 | | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300007 | Couldn't connect to server. |
| 2300028 | Timeout was reached. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300999 | Unknown Other Error. |
>**错误码说明:**
> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。
> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -120,7 +140,7 @@ httpRequest.request("EXAMPLE_URL", (err, data) => { ...@@ -120,7 +140,7 @@ httpRequest.request("EXAMPLE_URL", (err, data) => {
### request ### request
request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpResponse\>\):void request\(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpResponse\>\):void
根据URL地址和相关配置项,发起HTTP网络请求,使用callback方式作为异步方法。 根据URL地址和相关配置项,发起HTTP网络请求,使用callback方式作为异步方法。
...@@ -136,6 +156,46 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpR ...@@ -136,6 +156,46 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpR
| options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 | | options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 |
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 | | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300001 | Unsupported protocol. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**错误码说明:**
> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。
> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -163,7 +223,7 @@ httpRequest.request("EXAMPLE_URL", ...@@ -163,7 +223,7 @@ httpRequest.request("EXAMPLE_URL",
### request ### request
request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\> request\(url: string, options? : HttpRequestOptions\): Promise\<HttpResponse\>
根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。 根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。
...@@ -184,6 +244,45 @@ request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\> ...@@ -184,6 +244,45 @@ request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>
| :------------------------------------- | :-------------------------------- | | :------------------------------------- | :-------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 | | Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300001 | Unsupported protocol. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**错误码说明:**
> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。
> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
...@@ -222,6 +321,209 @@ destroy\(\): void ...@@ -222,6 +321,209 @@ destroy\(\): void
httpRequest.destroy(); httpRequest.destroy();
``` ```
### request2<sup>10+</sup>
request2(url: string, callback: AsyncCallback<void>): void
根据URL地址和相关配置项,发起HTTP网络请求并返回流式响应,使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url | string | 是 | 发起网络请求的URL地址。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300007 | Couldn't connect to server. |
| 2300028 | Timeout was reached. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300999 | Unknown Other Error. |
>**错误码说明:**
> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。
> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.request2("EXAMPLE_URL", (err) => {
if (!err) {
console.info(request2 OK!);
} else {
console.info("request2 ERROR : err = " + JSON.stringify(err));
}
})
```
### request2<sup>10+</sup>
request2(url: string, options: HttpRequestOptions, callback: AsyncCallback<void>): void
根据URL地址和相关配置项,发起HTTP网络请求并返回流式响应,使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url | string | 是 | 发起网络请求的URL地址。 |
| options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300001 | Unsupported protocol. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**错误码说明:**
> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。
> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.request2("EXAMPLE_URL",
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
},
readTimeout: 60000,
connectTimeout: 60000
}, (err) => {
if (!err) {
console.info(request2 OK!);
} else {
console.info("request2 ERROR : err = " + JSON.stringify(err));
}
})
```
### request2<sup>10+</sup>
request2\(url: string, options? : HttpRequestOptions\): Promise\<void\>
根据URL地址,发起HTTP网络请求并返回流式响应,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------ | ---- | ----------------------------------------------- |
| url | string | 是 | 发起网络请求的URL地址。 |
| options | HttpRequestOptions | 否 | 参考[HttpRequestOptions](#httprequestoptions)。 |
**返回值:**
| 类型 | 说明 |
| :------------------------------------- | :-------------------------------- |
| Promise\<void\> | 以Promise形式返回发起请求的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300001 | Unsupported protocol. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**错误码说明:**
> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。
> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:
**示例:**
```js
let promise = httpRequest.request("EXAMPLE_URL", {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
});
promise.then(() => {
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
...@@ -348,7 +650,148 @@ httpRequest.once('headersReceive', (header) => { ...@@ -348,7 +650,148 @@ httpRequest.once('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
``` ```
### on\('dataReceive'\)<sup>10+</sup>
on\(type: 'dataReceive', callback: Callback\<ArrayBuffer\>\): void
订阅HTTP流式响应数据接收事件。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | --------------------------------- |
| type | string | 是 | 订阅的事件类型,'dataReceive'。 |
| callback | AsyncCallback\<ArrayBuffer\> | 是 | 回调函数。 |
**示例:**
```js
httpRequest.on('dataReceive', (data) => {
console.info('dataReceive length: ' + JSON.stringify(data.byteLength));
});
```
### off\('dataReceive'\)<sup>10+</sup>
off\(type: 'dataReceive', callback?: Callback\<ArrayBuffer\>\): void
取消订阅HTTP流式响应数据接收事件。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------ | ---- | -------------------------------------- |
| type | string | 是 | 取消订阅的事件类型:'dataReceive'。 |
| callback | Callback\<ArrayBuffer\> | 否 | 回调函数。 |
**示例:**
```js
httpRequest.off('dataReceive');
```
### on\('dataEnd'\)<sup>10+</sup>
on\(type: 'dataEnd', callback: Callback\<void\>\): void
订阅HTTP流式响应数据接收完毕事件。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | --------------------------------- |
| type | string | 是 | 订阅的事件类型,'dataEnd'。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
httpRequest.on('dataReceive', () => {
console.info('Receive dataEnd!');
});
```
### off\('dataEnd'\)<sup>10+</sup>
off(type: 'dataEnd', callback?: Callback\<void\>): void
取消订阅HTTP流式响应数据接收完毕事件。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------ | ---- | -------------------------------------- |
| type | string | 是 | 取消订阅的事件类型:'dataEnd'。 |
| callback | Callback\<void\> | 否 | 回调函数。 |
**示例:**
```js
httpRequest.off('dataEnd');
```
### on\('dataProgress'\)<sup>10+</sup>
on\(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>\): void
订阅HTTP流式响应数据接收进度事件。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | --------------------------------- |
| type | string | 是 | 订阅的事件类型,'dataProgress'。 |
| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | 是 | 回调函数。 |
**示例:**
```js
httpRequest.on('dataProgress', (data) => {
if (!err) {
console.info('dataProgress:' + JSON.stringify(data));
}
});
```
### off\('dataProgress'\)<sup>10+</sup>
off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void
取消订阅HTTP流式响应数据接收进度事件。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------ | ---- | -------------------------------------- |
| type | string | 是 | 取消订阅的事件类型:'dataProgress'。 |
| callback | Callback\<{ receiveSize: number, totalSize: number }\> | 否 | 回调函数。 |
**示例:**
```js
httpRequest.off('dataProgress');
```
## HttpRequestOptions ## HttpRequestOptions
发起请求可选参数的类型和取值范围。 发起请求可选参数的类型和取值范围。
...@@ -359,13 +802,14 @@ httpRequest.once('headersReceive', (header) => { ...@@ -359,13 +802,14 @@ httpRequest.once('headersReceive', (header) => {
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | 否 | 请求方式。 | | method | [RequestMethod](#requestmethod) | 否 | 请求方式。 |
| extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | 否 | 发送请求的额外数据。<br />- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content。<br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。<sup>6+</sup><br />- 开发者传入string对象,开发者需要自行编码,将编码后的string传入。<sup>6+</sup> | | extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | 否 | 发送请求的额外数据。<br />- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content。<br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。<sup>6+</sup><br />- 开发者传入string对象,开发者需要自行编码,将编码后的string传入。<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 否 | 指定返回数据的类型。如果设置了此参数,系统将优先返回指定的类型。 | | expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 否 | 指定返回数据的类型。如果设置了此参数,系统将优先返回指定的类型。 |
| usingCache<sup>9+</sup> | boolean | 否 | 是否使用缓存,默认为true。 | | usingCache<sup>9+</sup> | boolean | 否 | 是否使用缓存,默认为true。 |
| priority<sup>9+</sup> | number | 否 | 优先级,范围\[1,1000],默认是1。 | | priority<sup>9+</sup> | number | 否 | 优先级,范围\[1,1000],默认是1。 |
| header | Object | 否 | HTTP请求头字段。默认{'Content-Type': 'application/json'}。 | | header | Object | 否 | HTTP请求头字段。默认{'Content-Type': 'application/json'}。 |
| readTimeout | number | 否 | 读取超时时间。单位为毫秒(ms),默认为60000ms。 | | readTimeout | number | 否 | 读取超时时间。单位为毫秒(ms),默认为60000ms。 |
| connectTimeout | number | 否 | 连接超时时间。单位为毫秒(ms),默认为60000ms。 | | connectTimeout | number | 否 | 连接超时时间。单位为毫秒(ms),默认为60000ms。 |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | 否 | 使用协议。默认值由系统自动指定。 | | usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | 否 | 使用协议。默认值由系统自动指定。 |
| usingProxy<sup>10+</sup> | boolean \| Object | 否 | 是否使用HTTP代理,默认为false,不使用代理。<br />- 当usingProxy为布尔类型true时,使用默认网络代理。<br />- 当usingProxy为object类型时,使用指定网络代理。 |
## RequestMethod ## RequestMethod
...@@ -438,9 +882,9 @@ request方法回调函数的返回值类型。 ...@@ -438,9 +882,9 @@ request方法回调函数的返回值类型。
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | 是 | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string | | result | string \| Object \| ArrayBuffer<sup>6+</sup> | 是 | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string |
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。 | | resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。 |
| responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。错误码参考[Response错误码](#response常用错误码) | | responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。 |
| header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<br/>- Content-Type:header['Content-Type'];<br />- Status-Line:header['Status-Line'];<br />- Date:header.Date/header['Date'];<br />- Server:header.Server/header['Server']; | | header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<br/>- Content-Type:header['Content-Type'];<br />- Status-Line:header['Status-Line'];<br />- Date:header.Date/header['Date'];<br />- Server:header.Server/header['Server']; |
| cookies<sup>8+</sup> | Array\<string\> | 是 | 服务器返回的 cookies。 | | cookies<sup>8+</sup> | string | 是 | 服务器返回的 cookies。 |
## http.createHttpResponseCache<sup>9+</sup> ## http.createHttpResponseCache<sup>9+</sup>
...@@ -492,10 +936,10 @@ flush(callback: AsyncCallback\<void>): void ...@@ -492,10 +936,10 @@ flush(callback: AsyncCallback\<void>): void
```js ```js
httpResponseCache.flush(err => { httpResponseCache.flush(err => {
if (err) { if (err) {
console.log('flush fail'); console.info('flush fail');
return; return;
} }
console.log('flush success'); console.info('flush success');
}); });
``` ```
...@@ -517,9 +961,9 @@ flush(): Promise\<void> ...@@ -517,9 +961,9 @@ flush(): Promise\<void>
```js ```js
httpResponseCache.flush().then(() => { httpResponseCache.flush().then(() => {
console.log('flush success'); console.info('flush success');
}).catch(err => { }).catch(err => {
console.log('flush fail'); console.info('flush fail');
}); });
``` ```
...@@ -542,10 +986,10 @@ delete(callback: AsyncCallback\<void>): void ...@@ -542,10 +986,10 @@ delete(callback: AsyncCallback\<void>): void
```js ```js
httpResponseCache.delete(err => { httpResponseCache.delete(err => {
if (err) { if (err) {
console.log('delete fail'); console.info('delete fail');
return; return;
} }
console.log('delete success'); console.info('delete success');
}); });
``` ```
### delete<sup>9+</sup> ### delete<sup>9+</sup>
...@@ -566,25 +1010,12 @@ delete(): Promise\<void> ...@@ -566,25 +1010,12 @@ delete(): Promise\<void>
```js ```js
httpResponseCache.delete().then(() => { httpResponseCache.delete().then(() => {
console.log('delete success'); console.info('delete success');
}).catch(err => { }).catch(err => {
console.log('delete fail'); console.info('delete fail');
}); });
``` ```
## Response常用错误码
| 错误码 | 说明 |
| ------ | ------------------------------------------------------------ |
| -1 | 参数错误。检查参数的个数与类型是否正确。 |
| 3 | URL格式错误。检查URL的格式与语法是否正确。 |
| 4 | 构建时无法找到内置的请求功能、协议或选项。一个功能或选项是不启用或明确禁用时,为了得到它的功能,你需要得到一个重建的libcurl。 |
| 5 | 无法解析代理,指定的代理服务器主机无法解析。建议排查:1、url地址是否正确。2、联网是否正常,网络是否可以和外部进行通信。3、是否有网络访问权限。 |
| 6 | 无法解析主机,指定的远程主机无法解析。建议排查:1、url地址是否正确。2、联网是否正常,网络是否可以和外部进行通信。3、是否有网络访问权限。 |
| 7 | 无法连接代理或主机。建议排查:1、端口号是否有问题。 2、查看本地是否开启http的代理影响的。 |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
## HttpDataType<sup>9+</sup> ## HttpDataType<sup>9+</sup>
http的数据类型。 http的数据类型。
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
网络连接管理提供管理网络一些基础能力,包括获取默认激活的数据网络、获取所有激活数据网络列表、开启关闭飞行模式、获取网络能力信息等功能。 网络连接管理提供管理网络一些基础能力,包括获取默认激活的数据网络、获取所有激活数据网络列表、开启关闭飞行模式、获取网络能力信息等功能。
> **说明:** > **说明:**
>
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 导入模块
...@@ -11,6 +10,40 @@ ...@@ -11,6 +10,40 @@
```js ```js
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
``` ```
## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
返回一个NetConnection对象,netSpecifier指定关注的网络的各项特征,timeout是超时时间(单位是毫秒),netSpecifier是timeout的必要条件,两者都没有则表示关注默认网络。
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| netSpecifier | [NetSpecifier](#netspecifier) | 否 | 指定网络的各项特征,不指定则关注默认网络。 |
| timeout | number | 否 | 获取netSpecifier指定的网络时的超时时间,仅netSpecifier存在时生效。 |
**返回值:**
| 类型 | 说明 |
| ------------------------------- | -------------------- |
| [NetConnection](#netconnection) | 所关注的网络的句柄。 |
**示例:**
```js
// 关注默认网络
let netConnection = connection.createNetConnection()
// 关注蜂窝网络
let netConnectionCellular = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
}
})
```
## connection.getDefaultNet ## connection.getDefaultNet
...@@ -26,14 +59,22 @@ getDefaultNet(callback: AsyncCallback\<NetHandle>): void ...@@ -26,14 +59,22 @@ getDefaultNet(callback: AsyncCallback\<NetHandle>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetHandle](#nethandle)> | 是 | 回调函数。 | | callback | AsyncCallback\<[NetHandle](#nethandle)> | 是 | 回调函数。当成功获取默认激活的数据网络时,err为undefined,data为默认激活的数据网络;否则为错误对象 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getDefaultNet(function (error, netHandle) { connection.getDefaultNet(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(netHandle)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -53,17 +94,25 @@ getDefaultNet(): Promise\<NetHandle> ...@@ -53,17 +94,25 @@ getDefaultNet(): Promise\<NetHandle>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<[NetHandle](#nethandle)> | 以Promise形式返回默认激活的数据网络。 | | Promise\<[NetHandle](#nethandle)> | 以Promise形式返回默认激活的数据网络。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (data) {
console.log(JSON.stringify(netHandle)) console.log(JSON.stringify(data))
}) })
``` ```
## connection.getDefaultNetSync<sup>9+</sup> ## connection.getDefaultNetSync<sup>9+</sup>
getDefaultNetSync(): NetHandle; getDefaultNetSync(): NetHandle
使用同步方法获取默认激活的数据网络。可以使用[getNetCapabilities](#connectiongetnetcapabilities)去获取网络的类型、拥有的能力等信息。 使用同步方法获取默认激活的数据网络。可以使用[getNetCapabilities](#connectiongetnetcapabilities)去获取网络的类型、拥有的能力等信息。
...@@ -77,58 +126,321 @@ getDefaultNetSync(): NetHandle; ...@@ -77,58 +126,321 @@ getDefaultNetSync(): NetHandle;
| --------- | ---------------------------------- | | --------- | ---------------------------------- |
| NetHandle | 以同步方式返回默认激活的数据网络。 | | NetHandle | 以同步方式返回默认激活的数据网络。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
let netHandle = connection.getDefaultNetSync(); let netHandle = connection.getDefaultNetSync();
``` ```
## connection.hasDefaultNet ## connection.getGlobalHttpProxy<sup>10+</sup>
hasDefaultNet(callback: AsyncCallback\<boolean>): void getGlobalHttpProxy(callback: AsyncCallback\<HttpProxy>): void
检查默认数据网络是否被激活,使用callback方式作为异步方法。如果有默认数据网路,可以使用[getDefaultNet](#connectiongetdefaultnet)去获取 获取网络的全局代理配置信息,使用callback方式作为异步方法
**需要权限**:ohos.permission.GET_NETWORK_INFO **系统接口**:此接口为系统接口。
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | -------------------------------------- | | --------- | ------------------------------------------------------------ | ---- | ---------------- |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,默认数据网络被激活返回true。 | | callback | AsyncCallback\<[HttpProxy](#httpproxy)> | 是 | 回调函数。当成功获取网络的全局代理配置信息时,err为undefined,data为网络的全局代理配置信息;否则为错误对象|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.hasDefaultNet(function (error, has) { connection.getGlobalHttpProxy((error,data) => {
console.log(JSON.stringify(error)) console.info(JSON.stringify(error));
console.log('has: ' + has) console.info(JSON.stringify(data));
}) })
``` ```
## connection.hasDefaultNet ## connection.getGlobalHttpProxy<sup>10+</sup>
hasDefaultNet(): Promise\<boolean> getGlobalHttpProxy(): Promise\<HttpProxy>;
检查默认数据网络是否被激活,使用Promise方式作为异步方法。如果有默认数据网路,可以使用[getDefaultNet](#connectiongetdefaultnet)去获取 获取网络的全局代理配置信息,使用Promise方式作为异步方法
**需要权限**:ohos.permission.GET_NETWORK_INFO **系统接口**:此接口为系统接口。
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ----------------- | ----------------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<boolean> | 以Promise形式返回,默认数据网络被激活返回true。 | | Promise\<[HttpProxy](#httpproxy)> | 以Promise形式返回网络的全局代理配置信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.hasDefaultNet().then(function (has) { connection.getGlobalHttpProxy().then((data) => {
console.log('has: ' + has) console.info(JSON.stringify(data));
}).catch(error => {
console.info(JSON.stringify(error));
})
```
## connection.setGlobalHttpProxy<sup>10+</sup>
setGlobalHttpProxy(httpProxy: HttpProxy, callback: AsyncCallback\<void>): void
设置网络全局Http代理配置信息,使用callback方式作为异步方法。
**系统接口**:此接口为系统接口。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| httpProxy | [HttpProxy](#httpproxy) | 是 | 网络全局Http代理配置信息 |
| callback | AsyncCallback\<void> | 是 | 回调函数。当成功设置网络全局Http代理配置信息时,err为undefined,否则为错误对象|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```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, (error, data) => {
console.info(JSON.stringify(error));
console.info(JSON.stringify(data));
});
```
## connection.setGlobalHttpProxy<sup>10+</sup>
setGlobalHttpProxy(httpProxy: HttpProxy): Promise\<void>;
设置网络全局Http代理配置信息,使用Promise方式作为异步方法。
**系统接口**:此接口为系统接口。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| httpProxy | [HttpProxy](#httpproxy) | 是 | 网络全局Http代理配置信息。 |
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 无返回值的Promise对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let exclusionStr="192.168,baidu.com"
let exclusionArray = exclusionStr.split(',');
let httpProxy = {
host: "192.168.xx.xxx",
port: 8080,
exclusionList: exclusionArray
}
connection.setGlobalHttpProxy(httpProxy).then((error, data) => {
console.info(JSON.stringify(data));
}).catch(error=>{
console.info(JSON.stringify(error));
})
```
## connection.getAppNet<sup>9+</sup>
getAppNet(callback: AsyncCallback\<NetHandle>): void
获取App绑定的网络信息,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| callback | AsyncCallback\<[NetHandle](#nethandle)> | 是 | 回调函数。当成功获取App绑定的网络信息时,err为undefined,data为获取到App绑定的网络信息;否则为错误对象|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
connection.getAppNet(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## connection.getAppNet<sup>9+</sup>
getAppNet(): Promise\<NetHandle>;
获取App绑定的网络信息,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetHandle](#nethandle)> | 以Promise形式返回App绑定的网络信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```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
绑定App到指定网络,绑定后的App只能通过指定网络访问外网,使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄。 |
| callback | AsyncCallback\<void> | 是 | 回调函数。当成功绑定App到指定网络时,err为undefined,否则为错误对象|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
connection.getDefaultNet(function (error, netHandle) {
connection.setAppNet(netHandle, (error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
})
```
## connection.SetAppNet<sup>9+</sup>
setAppNet(netHandle: NetHandle): Promise\<void>;
绑定App到指定网络,绑定后的App只能通过指定网络访问外网,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄。 |
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 无返回值的Promise对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
connection.getDefaultNet().then(function (netHandle) {
connection.setAppNet(netHandle).then((error, data) => {
console.log(JSON.stringify(data))
}).catch(error => {
console.log(JSON.stringify(error))
})
}) })
``` ```
...@@ -146,14 +458,22 @@ getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void ...@@ -146,14 +458,22 @@ getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | 是 | 回调函数。 | | callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | 是 | 回调函数。当成功获取所有处于连接状态的网络列表时,err为undefined,data为激活的数据网络列表;否则为错误对象 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getAllNets(function (error, nets) { connection.getAllNets(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(nets)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -173,11 +493,19 @@ getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt; ...@@ -173,11 +493,19 @@ getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt;
| -------- | -------- | | -------- | -------- |
| Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | 以Promise形式返回激活的数据网络列表。 | | Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | 以Promise形式返回激活的数据网络列表。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getAllNets().then(function (nets) { connection.getAllNets().then(function (data) {
console.log(JSON.stringify(nets)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -196,15 +524,25 @@ getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<Connectio ...@@ -196,15 +524,25 @@ getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<Connectio
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------------------------------------------ | ---- | ---------------- | | --------- | ------------------------------------------------------------ | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄。 | | netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄。 |
| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | 是 | 回调函数。 | | callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | 是 | 回调函数。当成功获取netHandle对应的网络的连接信息时,err为undefined,data为获取的网络连接信息;否则为错误对象|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getConnectionProperties(netHandle, function (error, info) { connection.getConnectionProperties(netHandle, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -231,12 +569,22 @@ getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties> ...@@ -231,12 +569,22 @@ getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties>
| ------------------------------------------------------- | --------------------------------- | | ------------------------------------------------------- | --------------------------------- |
| Promise\<[ConnectionProperties](#connectionproperties)> | 以Promise形式返回网络的连接信息。 | | Promise\<[ConnectionProperties](#connectionproperties)> | 以Promise形式返回网络的连接信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getConnectionProperties(netHandle).then(function (info) { connection.getConnectionProperties(netHandle).then(function (data) {
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -256,15 +604,25 @@ getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilitie ...@@ -256,15 +604,25 @@ getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilitie
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | --------------------------------------------------- | ---- | ---------------- | | --------- | --------------------------------------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄。 | | netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄。 |
| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | 是 | 回调函数。 | | callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | 是 | 回调函数。当成功获取netHandle对应的网络的能力信息时,err为undefined,data为获取到的网络能力信息;否则为错误对象 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getNetCapabilities(netHandle, function (error, info) { connection.getNetCapabilities(netHandle, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -291,12 +649,22 @@ getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities> ...@@ -291,12 +649,22 @@ getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities>
| --------------------------------------------- | --------------------------------- | | --------------------------------------------- | --------------------------------- |
| Promise\<[NetCapabilities](#netcapabilities)> | 以Promise形式返回网络的能力信息。 | | Promise\<[NetCapabilities](#netcapabilities)> | 以Promise形式返回网络的能力信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
connection.getNetCapabilities(netHandle).then(function (info) { connection.getNetCapabilities(netHandle).then(function (data) {
console.log(JSON.stringify(info)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -315,14 +683,22 @@ isDefaultNetMetered(callback: AsyncCallback\<boolean>): void ...@@ -315,14 +683,22 @@ isDefaultNetMetered(callback: AsyncCallback\<boolean>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,当前网络上的数据流量使用被计量返回true。 | | callback | AsyncCallback\<boolean> | 是 | 回调函数。当前网络上的数据流量使用被计量返回true。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.isDefaultNetMetered(function (error, has) { connection.isDefaultNetMetered(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log('has: ' + has) console.log('data: ' + data)
}) })
``` ```
...@@ -342,11 +718,216 @@ isDefaultNetMetered(): Promise\<boolean> ...@@ -342,11 +718,216 @@ isDefaultNetMetered(): Promise\<boolean>
| ----------------- | ----------------------------------------------- | | ----------------- | ----------------------------------------------- |
| Promise\<boolean> | 以Promise形式返回,当前网络上的数据流量使用被计量true。 | | Promise\<boolean> | 以Promise形式返回,当前网络上的数据流量使用被计量true。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.isDefaultNetMetered().then(function (has) { connection.isDefaultNetMetered().then(function (data) {
console.log('has: ' + has) console.log('data: ' + data)
})
```
## connection.hasDefaultNet
hasDefaultNet(callback: AsyncCallback\<boolean>): void
检查默认数据网络是否被激活,使用callback方式作为异步方法。如果有默认数据网路,可以使用[getDefaultNet](#connectiongetdefaultnet)去获取。
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | 是 | 回调函数。默认数据网络被激活返回true。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
connection.hasDefaultNet(function (error, data) {
console.log(JSON.stringify(error))
console.log('data: ' + data)
})
```
## connection.hasDefaultNet
hasDefaultNet(): Promise\<boolean>
检查默认数据网络是否被激活,使用Promise方式作为异步方法。如果有默认数据网路,可以使用[getDefaultNet](#connectiongetdefaultnet)去获取。
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| ----------------- | ----------------------------------------------- |
| Promise\<boolean> | 以Promise形式返回,默认数据网络被激活返回true。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
connection.hasDefaultNet().then(function (data) {
console.log('data: ' + data)
})
```
## connection.enableAirplaneMode
enableAirplaneMode(callback: AsyncCallback\<void>): void
开启飞行模式,使用callback方式作为异步方法。
**系统接口**:此接口为系统接口。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
connection.enableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.enableAirplaneMode
enableAirplaneMode(): Promise\<void>
开启飞行模式,使用Promise方式作为异步方法。
**系统接口**:此接口为系统接口。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 无返回值的Promise对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
connection.enableAirplaneMode().then(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode
disableAirplaneMode(callback: AsyncCallback\<void>): void
关闭飞行模式,使用callback方式作为异步方法。
**系统接口**:此接口为系统接口。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | 是 | 回调函数。当关闭飞行模式成功,err为undefined,否则为错误对象。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
connection.disableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode
disableAirplaneMode(): Promise\<void>
关闭飞行模式,使用Promise方式作为异步方法。
**系统接口**:此接口为系统接口。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 无返回值的Promise对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
connection.disableAirplaneMode().then(function (error) {
console.log(JSON.stringify(error))
}) })
``` ```
...@@ -366,7 +947,17 @@ reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): v ...@@ -366,7 +947,17 @@ reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): v
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 | | netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向网络管理报告网络处于可用状态成功,err为undefined,否则为错误对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
...@@ -400,6 +991,16 @@ reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt; ...@@ -400,6 +991,16 @@ reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | 无返回值的Promise对象。 | | Promise&lt;void&gt; | 无返回值的Promise对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -426,7 +1027,17 @@ reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;) ...@@ -426,7 +1027,17 @@ reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;)
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 | | netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向网络管理报告网络处于不可用状态成功,err为undefined,否则为错误对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
...@@ -460,6 +1071,16 @@ reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt; ...@@ -460,6 +1071,16 @@ reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | 无返回值的Promise对象。 | | Promise&lt;void&gt; | 无返回值的Promise对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -485,15 +1106,25 @@ getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): ...@@ -485,15 +1106,25 @@ getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>):
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | ------------------------------------------------- | ---- | ------------------ |
| host | string | 是 | 需要解析的主机名。 | | host | string | 是 | 需要解析的主机名。 |
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | 是 | 回调函数。 | | callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | 是 | 回调函数。当使用默认网络解析主机名成功获取所有IP地址,err为undefined,data为获取到的所有IP地址;否则为错误对象。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
let host = "xxxx"; let host = "xxxx";
connection.getAddressesByName(host, function (error, addresses) { connection.getAddressesByName(host, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(addresses)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -519,156 +1150,102 @@ getAddressesByName(host: string): Promise\<Array\<NetAddress>> ...@@ -519,156 +1150,102 @@ getAddressesByName(host: string): Promise\<Array\<NetAddress>>
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | 以Promise形式返回所有IP地址。 | | Promise\<Array\<[NetAddress](#netaddress)>> | 以Promise形式返回所有IP地址。 |
**示例:** **错误码:**
```js
let host = "xxxx";
connection.getAddressesByName(host).then(function (addresses) {
console.log(JSON.stringify(addresses))
})
```
## connection.enableAirplaneMode
enableAirplaneMode(callback: AsyncCallback\<void>): void
开启飞行模式,使用callback方式作为异步方法。
**系统接口**:此接口为系统接口。
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 | | 错误码ID | 错误信息 |
| -------- | ------------------------------------------------- | ---- | ------------------ | | ------- | ----------------------------- |
| callback | AsyncCallback\<void> | 是 | 回调函数。 | | 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.enableAirplaneMode(function (error) { let host = "xxxx";
console.log(JSON.stringify(error)) connection.getAddressesByName(host).then(function (data) {
}) console.log(JSON.stringify(data))
```
## connection.enableAirplaneMode
enableAirplaneMode(): Promise\<void>
开启飞行模式,使用Promise方式作为异步方法。
**系统接口**:此接口为系统接口。
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 无返回值的Promise对象。 |
**示例:**
```js
connection.enableAirplaneMode().then(function (error) {
console.log(JSON.stringify(error))
}) })
``` ```
## connection.disableAirplaneMode ## NetConnection
disableAirplaneMode(callback: AsyncCallback\<void>): void
关闭飞行模式,使用callback方式作为异步方法。
**系统接口**:此接口为系统接口。
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | 是 | 回调函数。 |
**示例:**
```js
connection.disableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode 网络连接的句柄。
disableAirplaneMode(): Promise\<void> ### register
关闭飞行模式,使用Promise方式作为异步方法。 register(callback: AsyncCallback\<void>): void
**系统接口**:此接口为系统接口。 订阅指定网络状态变化的通知。
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:** **参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是 | 回调函数。当订阅指定网络状态变化的通知成功,err为undefined,否则为错误对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 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. |
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 无返回值的Promise对象。 |
**示例:** **示例:**
```js ```js
connection.disableAirplaneMode().then(function (error) { netConnection.register(function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}) })
``` ```
## connection.createNetConnection ### unregister
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection unregister(callback: AsyncCallback\<void>): void
返回一个NetConnection对象,netSpecifier指定关注的网络的各项特征,timeout是超时时间(单位是毫秒),netSpecifier是timeout的必要条件,两者都没有则表示关注默认网络 取消订阅默认网络状态变化的通知
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | -------- | -------------------- | ---- | ---------- |
| netSpecifier | [NetSpecifier](#netspecifier) | 否 | 指定网络的各项特征,不指定则关注默认网络。 | | callback | AsyncCallback\<void> | 是 | 回调函数。当取消订阅指定网络状态变化的通知成功,err为undefined,否则为错误对象。 |
| timeout | number | 否 | 获取netSpecifier指定的网络时的超时时间,仅netSpecifier存在时生效。 |
**返回值:** **错误码:**
| 类型 | 说明 | | 错误码ID | 错误信息 |
| ------------------------------- | -------------------- | | ------- | ----------------------------- |
| [NetConnection](#netconnection) | 所关注的网络的句柄。 | | 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
| 2101007 | The same callback exists. |
**示例:** **示例:**
```js ```js
// 关注默认网络 netConnection.unregister(function (error) {
let netConnection = connection.createNetConnection() console.log(JSON.stringify(error))
// 关注蜂窝网络
let netConnectionCellular = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
}
}) })
``` ```
## NetConnection
网络连接的句柄。
### on('netAvailable') ### on('netAvailable')
on(type: 'netAvailable', callback: Callback\<NetHandle>): void on(type: 'netAvailable', callback: Callback\<NetHandle>): void
订阅网络可用事件。 订阅网络可用事件。
**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
**参数:** **参数:**
...@@ -676,21 +1253,37 @@ on(type: 'netAvailable', callback: Callback\<NetHandle>): void ...@@ -676,21 +1253,37 @@ on(type: 'netAvailable', callback: Callback\<NetHandle>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅事件,固定为'netAvailable'。<br>netAvailable:数据网络可用事件。 | | type | string | 是 | 订阅事件,固定为'netAvailable'。<br>netAvailable:数据网络可用事件。 |
| callback | Callback\<[NetHandle](#nethandle)> | 是 | 回调函数| | callback | Callback\<[NetHandle](#nethandle)> | 是 | 回调函数,返回数据网络句柄。|
**示例:** **示例:**
```js ```js
netConnection.on('netAvailable', function (data) { // 创建NetConnection对象
let netCon = connection.createNetConnection()
// 先使用register接口注册订阅事件
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// 订阅网络可用事件。调用register后,才能接收到此事件通知
netCon.on('netAvailable', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// 使用unregister接口取消订阅
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
订阅网络能力变化事件。 订阅网络阻塞状态事件,使用callback方式作为异步方法。
**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
...@@ -698,22 +1291,38 @@ on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, net ...@@ -698,22 +1291,38 @@ on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, net
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅事件,固定为'netCapabilitiesChange'。<br/>netCapabilitiesChange:网络能力变化事件。 | | type | string | 是 | 订阅事件,固定为'netBlockStatusChange'。<br/>netBlockStatusChange:网络阻塞状态事件。 |
| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | 是 | 回调函数。 | | callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | 是 | 回调函数,返回数据网络句柄(netHandle),及网络堵塞状态(blocked)。|
**示例:** **示例:**
```js ```js
netConnection.on('netCapabilitiesChange', function (data) { // 创建NetConnection对象
let netCon = connection.createNetConnection()
// 先使用register接口注册订阅事件
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// 订阅网络阻塞状态事件。调用register后,才能接收到此事件通知
netCon.on('netBlockStatusChange', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// 使用unregister接口取消订阅
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
订阅网络连接信息变化事件。 订阅网络能力变化事件。
**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
...@@ -721,22 +1330,38 @@ on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHan ...@@ -721,22 +1330,38 @@ on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHan
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅事件,固定为'netConnectionPropertiesChange'。<br/>netConnectionPropertiesChange:网络连接信息变化事件。 | | type | string | 是 | 订阅事件,固定为'netCapabilitiesChange'。<br/>netCapabilitiesChange:网络能力变化事件。 |
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | 是 | 回调函数。 | | callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | 是 | 回调函数,返回数据网络句柄(netHandle)和网络的能力信息(netCap)。|
**示例:** **示例:**
```js ```js
netConnection.on('netConnectionPropertiesChange', function (data) { // 创建NetConnection对象
let netCon = connection.createNetConnection()
// 先使用register接口注册订阅事件
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// 订阅网络能力变化事件。调用register后,才能接收到此事件通知
netCon.on('netCapabilitiesChange', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// 使用unregister接口取消订阅
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
订阅网络阻塞状态事件,使用callback方式作为异步方法。 订阅网络连接信息变化事件。
**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
...@@ -744,15 +1369,29 @@ on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, b ...@@ -744,15 +1369,29 @@ on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, b
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅事件,固定为'netBlockStatusChange'。<br/>netBlockStatusChange:网络阻塞状态事件。 | | type | string | 是 | 订阅事件,固定为'netConnectionPropertiesChange'。<br/>netConnectionPropertiesChange:网络连接信息变化事件。 |
| callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | 是 | 回调函数。 | | callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | 是 | 回调函数,返回数据网络句柄(netHandle)和网络的连接信息(connectionProperties)|
**示例:** **示例:**
```js ```js
netConnection.on('netBlockStatusChange', function (data) { // 创建NetConnection对象
let netCon = connection.createNetConnection()
// 先使用register接口注册订阅事件
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// 订阅网络连接信息变化事件。调用register后,才能接收到此事件通知
netCon.on('netConnectionPropertiesChange', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// 使用unregister接口取消订阅
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### on('netLost') ### on('netLost')
...@@ -761,6 +1400,8 @@ on(type: 'netLost', callback: Callback\<NetHandle>): void ...@@ -761,6 +1400,8 @@ on(type: 'netLost', callback: Callback\<NetHandle>): void
订阅网络丢失事件。 订阅网络丢失事件。
**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
**参数:** **参数:**
...@@ -768,15 +1409,28 @@ on(type: 'netLost', callback: Callback\<NetHandle>): void ...@@ -768,15 +1409,28 @@ on(type: 'netLost', callback: Callback\<NetHandle>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅事件,固定为'netLost'。<br/>netLost:网络严重中断或正常断开事件。 | | type | string | 是 | 订阅事件,固定为'netLost'。<br/>netLost:网络严重中断或正常断开事件。 |
| callback | Callback\<[NetHandle](#nethandle)> | 是 | 回调函数| | callback | Callback\<[NetHandle](#nethandle)> | 是 | 回调函数,数据网络句柄(netHandle)|
**示例:** **示例:**
```js ```js
let netConnection1 = connection.createNetConnection() // 创建NetConnection对象
netConnection1.on('netLost', function (data) { let netCon = connection.createNetConnection()
// 先使用register接口注册订阅事件
netCon.register(function (error) {
console.log(JSON.stringify(error))
})
// 订阅网络丢失事件。调用register后,才能接收到此事件通知
netCon.on('netLost', function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
// 使用unregister接口取消订阅
netCon.unregister(function (error) {
console.log(JSON.stringify(error))
})
``` ```
### on('netUnavailable') ### on('netUnavailable')
...@@ -785,6 +1439,8 @@ on(type: 'netUnavailable', callback: Callback\<void>): void ...@@ -785,6 +1439,8 @@ on(type: 'netUnavailable', callback: Callback\<void>): void
订阅网络不可用事件。 订阅网络不可用事件。
**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
**参数:** **参数:**
...@@ -792,58 +1448,26 @@ on(type: 'netUnavailable', callback: Callback\<void>): void ...@@ -792,58 +1448,26 @@ on(type: 'netUnavailable', callback: Callback\<void>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------- | ---- | ------------------------------------------------------------ | | -------- | --------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅事件,固定为'netUnavailable'。<br/>netUnavailable:网络不可用事件。 | | type | string | 是 | 订阅事件,固定为'netUnavailable'。<br/>netUnavailable:网络不可用事件。 |
| callback | Callback\<void> | 是 | 回调函数| | callback | Callback\<void> | 是 | 回调函数,无返回结果。|
**示例:** **示例:**
```js ```js
netConnection.on('netUnavailable', function (data) { // 创建NetConnection对象
console.log(JSON.stringify(data)) let netCon = connection.createNetConnection()
})
```
### register
register(callback: AsyncCallback\<void>): void
订阅指定网络状态变化的通知。
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是 | 回调函数。 |
**示例:** // 先使用register接口注册订阅事件
netCon.register(function (error) {
```js
netConnection.register(function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}) })
```
### unregister
unregister(callback: AsyncCallback\<void>): void
取消订阅默认网络状态变化的通知。
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是 | 回调函数。 |
**示例:** // 订阅网络不可用事件。调用register后,才能接收到此事件通知
netCon.on('netUnavailable', function (data) {
console.log(JSON.stringify(data))
})
```js // 使用unregister接口取消订阅
netConnection.unregister(function (error) { netCon.unregister(function (error) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
}) })
``` ```
...@@ -864,7 +1488,7 @@ netConnection.unregister(function (error) { ...@@ -864,7 +1488,7 @@ netConnection.unregister(function (error) {
### bindSocket<sup>9+</sup> ### bindSocket<sup>9+</sup>
bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void; bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void
将TCPSocket或UDPSocket绑定到当前网络,使用callback方式作为异步方法。 将TCPSocket或UDPSocket绑定到当前网络,使用callback方式作为异步方法。
...@@ -875,24 +1499,33 @@ bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): ...@@ -875,24 +1499,33 @@ bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>):
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------------------------ | ---- | -------------------------------| | ----------- | ------------------------ | ---- | -------------------------------|
| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | 是 | 待绑定的TCPSocket或UDPSocket对象。| | socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | 是 | 待绑定的TCPSocket或UDPSocket对象。|
| callback | AsyncCallback\<void> | 是 | 回调函数 | | callback | AsyncCallback\<void> | 是 | 回调函数。当TCPSocket或UDPSocket成功绑定到当前网络,err为undefined,否则为错误对象。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
import socket from "@ohos.net.socket"; import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{ connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
let socketType = "TCPSocket"; let socketType = "TCPSocket";
if (socketType == "TCPSocket") { if (socketType == "TCPSocket") {
tcp.bind({ tcp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
netHandle.bindSocket(tcp, (error, data)=>{ netHandle.bindSocket(tcp, (error, data) => {
if (error) { if (error) {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
} else { } else {
...@@ -902,19 +1535,19 @@ connection.getDefaultNet().then((netHandle)=>{ ...@@ -902,19 +1535,19 @@ connection.getDefaultNet().then((netHandle)=>{
}) })
} else { } else {
let callback = value => { let callback = value => {
console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
} }
udp.on('message', callback); udp.on('message', callback);
udp.bind({ udp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); });
netHandle.bindSocket(udp,(error, data)=>{ netHandle.bindSocket(udp, (error, data) => {
if (error) { if (error) {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
} else { } else {
...@@ -946,49 +1579,54 @@ bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>; ...@@ -946,49 +1579,54 @@ bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>;
| -------------- | ---------------------- | | -------------- | ---------------------- |
| Promise\<void> | 无返回值的Promise对象。 | | Promise\<void> | 无返回值的Promise对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
import socket from "@ohos.net.socket"; import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{ connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
let socketType = "TCPSocket"; let socketType = "TCPSocket";
if (socketType == "TCPSocket") { if (socketType == "TCPSocket") {
tcp.bind({ tcp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
netHandle.bindSocket(tcp).then((err, data) => { netHandle.bindSocket(tcp).then((data) => {
if (err) { console.log(JSON.stringify(data));
console.log(JSON.stringify(err)); }).catch(error => {
} else { console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
}
}) })
}) })
} else { } else {
let callback = value => { let callback = value => {
console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
} }
udp.on('message', callback); udp.on('message', callback);
udp.bind({ udp.bind({
address: '192.168.xx.xxx', port: xxxx, family: 1 address: '192.168.xx.xxx', port: 8080, family: 1
}, err => { }, error => {
if (err) { if (error) {
console.log('bind fail'); console.log('bind fail');
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
netHandle.bindSocket(udp).then((err, data) => { netHandle.bindSocket(udp).then((data) => {
if (err) { console.log(JSON.stringify(data));
console.log(JSON.stringify(err)); }).catch(error => {
} else { console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
}
}) })
}) })
} }
...@@ -1010,16 +1648,26 @@ getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): ...@@ -1010,16 +1648,26 @@ getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>):
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | ------------------------------------------------- | ---- | ------------------ |
| host | string | 是 | 需要解析的主机名。 | | host | string | 是 | 需要解析的主机名。 |
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | 是 | 回调函数 | | callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | 是 | 回调函数。当使用对应网络解析主机名成功获取所有IP地址,err为undefined,data为获取到的所有IP地址;否则为错误对象。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressesByName(host, function (error, addresses) { netHandle.getAddressesByName(host, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(addresses)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -1046,13 +1694,23 @@ getAddressesByName(host: string): Promise\<Array\<NetAddress>> ...@@ -1046,13 +1694,23 @@ getAddressesByName(host: string): Promise\<Array\<NetAddress>>
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | 以Promise形式返回所有IP地址。 | | Promise\<Array\<[NetAddress](#netaddress)>> | 以Promise形式返回所有IP地址。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressesByName(host).then(function (addresses) { netHandle.getAddressesByName(host).then(function (data) {
console.log(JSON.stringify(addresses)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -1072,16 +1730,26 @@ getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void ...@@ -1072,16 +1730,26 @@ getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------ | | -------- | ----------------------------------------- | ---- | ------------------ |
| host | string | 是 | 需要解析的主机名。 | | host | string | 是 | 需要解析的主机名。 |
| callback | AsyncCallback\<[NetAddress](#netaddress)> | 是 | 回调函数。 | | callback | AsyncCallback\<[NetAddress](#netaddress)> | 是 | 回调函数。当使用对应网络解析主机名获取第一个IP地址成功,err为undefined,data为获取的第一个IP地址;否则为错误对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressByName(host, function (error, address) { netHandle.getAddressByName(host, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(address)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
...@@ -1108,41 +1776,27 @@ getAddressByName(host: string): Promise\<NetAddress> ...@@ -1108,41 +1776,27 @@ getAddressByName(host: string): Promise\<NetAddress>
| ----------------------------------- | ------------------------------- | | ----------------------------------- | ------------------------------- |
| Promise\<[NetAddress](#netaddress)> | 以Promise形式返回第一个IP地址。 | | Promise\<[NetAddress](#netaddress)> | 以Promise形式返回第一个IP地址。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:** **示例:**
```js ```js
connection.getDefaultNet().then(function (netHandle) { connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx"; let host = "xxxx";
netHandle.getAddressByName(host).then(function (address) { netHandle.getAddressByName(host).then(function (data) {
console.log(JSON.stringify(address)) console.log(JSON.stringify(data))
}) })
}) })
``` ```
## NetSpecifier
提供承载数据网络能力的实例。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 名称 | 类型 | 必填 | 说明 |
| ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| netCapabilities | [NetCapabilities](#netcapabilities) | 是 | 存储数据网络的传输能力和承载类型。 |
| bearerPrivateIdentifier | string | 否 | 网络标识符,Wi-Fi网络的标识符是"wifi",蜂窝网络的标识符是"slot0"(对应SIM卡1)。 |
## NetCapabilities
网络的能力集。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 名称 | 类型 | 必填 | 说明 |
| --------------------- | ---------------------------------- | --- | ------------------------ |
| linkUpBandwidthKbps | number | 否 | 上行(设备到网络)带宽。 |
| linkDownBandwidthKbps | number | 否 | 下行(网络到设备)带宽。 |
| networkCap | Array\<[NetCap](#netcap)> | 否 | 网络具体能力。 |
| bearerTypes | Array\<[NetBearType](#netbeartype)> | 是 | 网络类型。 |
## NetCap ## NetCap
网络具体能力。 网络具体能力。
...@@ -1169,6 +1823,42 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -1169,6 +1823,42 @@ connection.getDefaultNet().then(function (netHandle) {
| BEARER_WIFI | 1 | Wi-Fi网络。 | | BEARER_WIFI | 1 | Wi-Fi网络。 |
| BEARER_ETHERNET | 3 | 以太网网络。 | | BEARER_ETHERNET | 3 | 以太网网络。 |
## HttpProxy<sup>10+</sup>
网络全局代理配置信息
**系统能力**:SystemCapability.Communication.NetManager.Core
| 名称 | 类型 | 必填 | 说明 |
| ------ | ------ | --- |------------------------- |
| host | string | 否 | 代理服务器主机名。 |
| port | number | 否 | 主机端口。 |
| exclusionList | Array<string> | 否 | 不使用代理服务器的屏蔽列表。 |
## NetSpecifier
提供承载数据网络能力的实例。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 名称 | 类型 | 必填 | 说明 |
| ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| netCapabilities | [NetCapabilities](#netcapabilities) | 是 | 存储数据网络的传输能力和承载类型。 |
| bearerPrivateIdentifier | string | 否 | 网络标识符,Wi-Fi网络的标识符是"wifi",蜂窝网络的标识符是"slot0"(对应SIM卡1)。 |
## NetCapabilities
网络的能力集。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 名称 | 类型 | 必填 | 说明 |
| --------------------- | ---------------------------------- | --- | ------------------------ |
| linkUpBandwidthKbps | number | 否 | 上行(设备到网络)带宽。 |
| linkDownBandwidthKbps | number | 否 | 下行(网络到设备)带宽。 |
| networkCap | Array\<[NetCap](#netcap)> | 否 | 网络具体能力。 |
| bearerTypes | Array\<[NetBearType](#netbeartype)> | 是 | 网络类型。 |
## ConnectionProperties ## ConnectionProperties
网络连接信息。 网络连接信息。
...@@ -1181,20 +1871,9 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -1181,20 +1871,9 @@ connection.getDefaultNet().then(function (netHandle) {
| domains | string | 是 |所属域,默认""。 | | domains | string | 是 |所属域,默认""。 |
| linkAddresses | Array\<[LinkAddress](#linkaddress)> | 是 |链路信息。 | | linkAddresses | Array\<[LinkAddress](#linkaddress)> | 是 |链路信息。 |
| routes | Array\<[RouteInfo](#routeinfo)> | 是 |路由信息。 | | routes | Array\<[RouteInfo](#routeinfo)> | 是 |路由信息。 |
| dnses | Array\<[NetAddress](#netaddress)>; | 是 |网络地址,参考[NetAddress](#netaddress)。 | | dnses | Array\<[NetAddress](#netaddress)> | 是 |网络地址,参考[NetAddress](#netaddress)。 |
| mtu | number | 是 |最大传输单元。 | | mtu | number | 是 |最大传输单元。 |
## LinkAddress
网络链路信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 名称 | 类型 | 必填 |说明 |
| ------------ | ----------------------- |---- |-------------------- |
| address | [NetAddress](#netaddress) | 是 | 链路地址。 |
| prefixLength | number | 是 |链路地址前缀的长度。 |
## RouteInfo ## RouteInfo
网络路由信息。 网络路由信息。
...@@ -1209,6 +1888,17 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -1209,6 +1888,17 @@ connection.getDefaultNet().then(function (netHandle) {
| hasGateway | boolean | 是 |是否有网关。 | | hasGateway | boolean | 是 |是否有网关。 |
| isDefaultRoute | boolean | 是 |是否为默认路由。 | | isDefaultRoute | boolean | 是 |是否为默认路由。 |
## LinkAddress
网络链路信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 名称 | 类型 | 必填 |说明 |
| ------------ | ----------------------- |---- |-------------------- |
| address | [NetAddress](#netaddress) | 是 | 链路地址。 |
| prefixLength | number | 是 |链路地址前缀的长度。 |
## NetAddress ## NetAddress
网络地址。 网络地址。
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
以太网连接管理主要提供有线网络能力,提供设置有线网络的IP地址,子网掩码,网关,DNS等信息 以太网连接管理主要提供有线网络能力,提供设置有线网络的IP地址,子网掩码,网关,DNS等信息
> **说明:** > **说明:**
>
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 导入模块
...@@ -32,18 +31,37 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac ...@@ -32,18 +31,37 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac
| ic | [InterfaceConfiguration](#interfaceconfiguration) | 是 | 要设置的网络接口配置信息 | | ic | [InterfaceConfiguration](#interfaceconfiguration) | 是 | 要设置的网络接口配置信息 |
| callback | AsyncCallback\<void> | 是 | 回调函数,成功无返回,失败返回对应错误码。 | | callback | AsyncCallback\<void> | 是 | 回调函数,成功无返回,失败返回对应错误码。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
| 2201006 | Device disconnected. |
| 2201007 | Failed to write the user configuration. |
**示例:** **示例:**
```js ```js
ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", ethernet.setIfaceConfig("eth0", {
gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}, mode: 0,
(error) => { ipAddr: "192.168.xx.xxx",
if (error) { route: "192.168.xx.xxx",
console.log("setIfaceConfig callback error = " + error); gateway: "192.168.xx.xxx",
} else { netMask: "255.255.255.0",
console.log("setIfaceConfig callback ok "); dnsServers: "1.1.1.1",
} domain: "2.2.2.2"
}); }, (error) => {
if (error) {
console.log("setIfaceConfig callback error = " + JSON.stringify(error));
} else {
console.log("setIfaceConfig callback ok ");
}
});
``` ```
## ethernet.setIfaceConfig ## ethernet.setIfaceConfig
...@@ -71,14 +89,34 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\<void> ...@@ -71,14 +89,34 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\<void>
| ------------------- | ----------------------------------------------------------- | | ------------------- | ----------------------------------------------------------- |
| Promise\<void> | 以Promise形式返回执行结果。成功无返回,失败返回对应错误码。 | | Promise\<void> | 以Promise形式返回执行结果。成功无返回,失败返回对应错误码。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
| 2201006 | Device disconnected. |
| 2201007 | Failed to write the user configuration. |
**示例:** **示例:**
```js ```js
ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", ethernet.setIfaceConfig("eth0", {
gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}).then(() => { mode: 0,
ipAddr: "192.168.xx.xxx",
route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx",
netMask: "255.255.255.0",
dnsServers: "1.1.1.1",
domain: "2.2.2.2"
}).then(() => {
console.log("setIfaceConfig promiss ok "); console.log("setIfaceConfig promiss ok ");
}).catch((error) => { }).catch(error => {
console.log("setIfaceConfig promiss error = " + error); console.log("setIfaceConfig promiss error = " + JSON.stringify(error));
}); });
``` ```
...@@ -101,20 +139,31 @@ getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): ...@@ -101,20 +139,31 @@ getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>):
| iface | string | 是 | 指定网络接口 | | iface | string | 是 | 指定网络接口 |
| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | 是 | 回调函数,返回指定网络接口信息 | | callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | 是 | 回调函数,返回指定网络接口信息 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**示例:** **示例:**
```js ```js
ethernet.getIfaceConfig("eth0", (error, value) => { ethernet.getIfaceConfig("eth0", (error, value) => {
if (error) { if (error) {
console.log("getIfaceConfig callback error = " + error); console.log("getIfaceConfig callback error = " + JSON.stringify(error));
} else { } else {
console.log("getIfaceConfig callback mode = " + value.mode); console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode));
console.log("getIfaceConfig callback ipAddr = " + value.ipAddr); console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr));
console.log("getIfaceConfig callback routeAddr = " + value.routeAddr); console.log("getIfaceConfig callback route = " + JSON.stringify(value.route));
console.log("getIfaceConfig callback gateAddr = " + value.gateAddr); console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway));
console.log("getIfaceConfig callback maskAddr = " + value.maskAddr); console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask));
console.log("getIfaceConfig callback dns0Addr = " + value.dns0Addr); console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers));
console.log("getIfaceConfig callback dns1Addr = " + value.dns1Addr); console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain));
} }
}); });
``` ```
...@@ -143,19 +192,30 @@ getIfaceConfig(iface: string): Promise\<InterfaceConfiguration> ...@@ -143,19 +192,30 @@ getIfaceConfig(iface: string): Promise\<InterfaceConfiguration>
| --------------------------------- | ---------------------------------- | | --------------------------------- | ---------------------------------- |
| Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | 以Promise形式返回接口信息。 | | Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | 以Promise形式返回接口信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**示例:** **示例:**
```js ```js
ethernet.getIfaceConfig("eth0").then((data) => { ethernet.getIfaceConfig("eth0").then((data) => {
console.log("getIfaceConfig promiss mode = " + data.mode); console.log("getIfaceConfig promiss mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promiss ipAddr = " + data.ipAddr); console.log("getIfaceConfig promiss ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promiss routeAddr = " + data.routeAddr); console.log("getIfaceConfig promiss route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promiss gateAddr = " + data.gateAddr); console.log("getIfaceConfig promiss gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promiss maskAddr = " + data.maskAddr); console.log("getIfaceConfig promiss netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promiss dns0Addr = " + data.dns0Addr); console.log("getIfaceConfig promiss dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promiss dns1Addr = " + data.dns1Addr); console.log("getIfaceConfig promiss domain = " + JSON.stringify(data.domain));
}).catch((error) => { }).catch(error => {
console.log("getIfaceConfig promiss error = " + error); console.log("getIfaceConfig promiss error = " + JSON.stringify(error));
}); });
``` ```
...@@ -178,15 +238,26 @@ isIfaceActive(iface: string, callback: AsyncCallback\<number>): void ...@@ -178,15 +238,26 @@ isIfaceActive(iface: string, callback: AsyncCallback\<number>): void
| iface | string | 是 | 接口名。为空时代表查询是否存在激活接口 | | iface | string | 是 | 接口名。为空时代表查询是否存在激活接口 |
| callback | AsyncCallback\<number> | 是 | 回调函数,已激活:1,未激活:0,其他为获取失败错误码。 | | callback | AsyncCallback\<number> | 是 | 回调函数,已激活:1,未激活:0,其他为获取失败错误码。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**示例:** **示例:**
```js ```js
ethernet.isIfaceActive("eth0", (error, value) => { ethernet.isIfaceActive("eth0", (error, value) => {
if (error) { if (error) {
console.log("whether2Activate callback error = " + error); console.log("whether2Activate callback error = " + JSON.stringify(error));
} else { } else {
console.log("whether2Activate callback = " + value); console.log("whether2Activate callback = " + JSON.stringify(value));
} }
}); });
``` ```
...@@ -214,13 +285,24 @@ isIfaceActive(iface: string): Promise\<number> ...@@ -214,13 +285,24 @@ isIfaceActive(iface: string): Promise\<number>
| ----------------| ------------------------------------------------------------------ | | ----------------| ------------------------------------------------------------------ |
| Promise\<number> | 以Promise形式返回获取结果。已激活:1,未激活:0,其他为获取失败错误码。| | Promise\<number> | 以Promise形式返回获取结果。已激活:1,未激活:0,其他为获取失败错误码。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**示例:** **示例:**
```js ```js
ethernet.isIfaceActive("eth0").then((data) => { ethernet.isIfaceActive("eth0").then((data) => {
console.log("isIfaceActive promiss = " + data); console.log("isIfaceActive promiss = " + JSON.stringify(data));
}).catch((error) => { }).catch(error => {
console.log("isIfaceActive promiss error = " + error); console.log("isIfaceActive promiss error = " + JSON.stringify(error));
}); });
``` ```
...@@ -242,18 +324,26 @@ getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void ...@@ -242,18 +324,26 @@ getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void
| -------- | ------------------------------------ | ---- | ------------------------------ | | -------- | ------------------------------------ | ---- | ------------------------------ |
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回值为对应接口名。 | | callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回值为对应接口名。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
ethernet.getAllActiveIfaces((error, value) => { ethernet.getAllActiveIfaces((error, value) => {
if (error) { if (error) {
console.log("getAllActiveIfaces callback error = " + error); console.log("getAllActiveIfaces callback error = " + JSON.stringify(error));
} else { } else {
console.log("getAllActiveIfaces callback value.length = " + value.length); console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length));
for (let i = 0; i < value.length; i++) { for (let i = 0; i < value.length; i++) {
console.log("getAllActiveIfaces callback = " + value[i]); console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i]));
}
} }
}
}); });
``` ```
...@@ -275,16 +365,24 @@ getAllActiveIfaces(): Promise\<Array\<string>> ...@@ -275,16 +365,24 @@ getAllActiveIfaces(): Promise\<Array\<string>>
| ------------------------------ | ----------------------------------------------- | | ------------------------------ | ----------------------------------------------- |
| Promise\<Array\<string>> | 以Promise形式返回获取结果。返回值为对应接口名。 | | Promise\<Array\<string>> | 以Promise形式返回获取结果。返回值为对应接口名。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
ethernet.getAllActiveIfaces().then((data) => { ethernet.getAllActiveIfaces().then((data) => {
console.log("getAllActiveIfaces promiss data.length = " + data.length); console.log("getAllActiveIfaces promiss data.length = " + JSON.stringify(data.length));
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces promiss = " + data[i]); console.log("getAllActiveIfaces promiss = " + JSON.stringify(data[i]));
} }
}).catch((error) => { }).catch(error => {
console.log("getAllActiveIfaces promiss error = " + error); console.log("getAllActiveIfaces promiss error = " + JSON.stringify(error));
}); });
``` ```
......
# @ohos.net.policy (网络策略管理)
网络策略管理通过对用户使用数据流量进行控制管理,采用防火墙技术实现网络策略的管理。
> **说明:**
>
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```js
import policy from '@ohos.net.policy'
```
## policy.setBackgroundPolicy
setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\<void>): void
设置后台网络策略,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| isAllowed | boolean | 是 | 是否允许应用后台使用数据 |
| callback | AsyncCallback\<void> | 是 | 回调函数,成功返回设置后台网络策略的结果,失败返回错误码错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => {
this.callBack(error, data);
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.setBackgroundPolicy
setBackgroundPolicy(isAllowed: boolean): Promise\<void>
设置后台网络策略,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| isAllowed | boolean | 是 | 是否允许应用后台使用数据 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回设定结果,失败返回错误码错误信息。 |
**示例:**
```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.isBackgroundAllowed
isBackgroundAllowed(callback: AsyncCallback\<boolean>): void
获取后台网络策略,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true代表后台策略为允许。失败返回错误码错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.isBackgroundAllowed((error, data) => {
this.callBack(error, data);
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.isBackgroundAllowed
isBackgroundAllowed(): Promise\<boolean>;
获取后台网络策略,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<boolean> | 以Promise形式返回设定结果。 返回true代表后台策略为允许。失败返回错误码错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.isBackgroundAllowed().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setPolicyByUid
setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\<void>): void
设置对应uid应用的访问计量网络的策略,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | 应用的唯一标识符 |
| policy | [NetUidPolicy](#netuidpolicy) | 是 | 应用对应的策略 |
| callback | AsyncCallback\<void> | 是 | 回调函数,成功返回设定结果。失败返回错误码错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
}
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (error, data) => {
this.callBack(error, data);
});
```
## policy.setPolicyByUid
setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\<void>;
设置对应uid应用的访问计量网络的策略,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | 应用的唯一标识符 |
| policy | [NetUidPolicy](#netuidpolicy) | 是 | 应用对应的策略 |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回设定结果。失败返回错误码错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
}
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getPolicyByUid
getPolicyByUid(uid: number, callback: AsyncCallback\<NetUidPolicy>): void
通过应用uid获取策略,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
| callback | AsyncCallback\<[NetUidPolicy](#netuidpolicy)> | 是 | 回调函数,成功返回获取策略结果,失败返回错误码错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => {
this.callBack(error, data);
});
```
## policy.getPolicyByUid
getPolicyByUid(uid: number): Promise\<NetUidPolicy>;
通过应用uid获取策略,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetUidPolicy](#netuidpolicy)> | 以Promise形式返回获取策略结果。失败返回错误码错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getUidsByPolicy
getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\<Array\<number>>): void
通过策略获取设置这一策略的应用uid数组,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| policy | [NetUidPolicy](#netuidpolicy) | 是 | 应用对应的计量网络下的策略 |
| callback | AsyncCallback\<Array\<number>> | 是 | 回调函数,成功返回应用的uid数组,失败返回错误码错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => {
this.callBack(error, data);
});
```
## policy.getUidsByPolicy
function getUidsByPolicy(policy: NetUidPolicy): Promise\<Array\<number>>;
通过策略获取设置这一策略的应用uid数组,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| policy | [NetUidPolicy](#netuidpolicy) | 是 | app对应的计量网络下的策略 |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<number>> | 以Promise形式返回应用的uid数组,失败返回错误码错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getNetQuotaPolicies
getNetQuotaPolicies(callback: AsyncCallback\<Array\<NetQuotaPolicy>>): void
获取计量网络策略,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<Array\<[NetQuotaPolicy](#netquotapolicy)>> | 是 | 回调函数,返回获取结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getNetQuotaPolicies((error, data) => {
this.callBack(error, data);
});
```
## policy.getNetQuotaPolicies
getNetQuotaPolicies(): Promise\<Array\<NetQuotaPolicy>>;
获取计量网络策略,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<[NetQuotaPolicy](#netquotapolicy)>> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getNetQuotaPolicies().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setNetQuotaPolicies
setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>, callback: AsyncCallback\<void>): void
设置计量网络策略,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | 是 | 计量网络策略 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes),
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction};
this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => {
this.callBack(error, data);
});
```
## policy.setNetQuotaPolicies
setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>): Promise\<void>;
设置计量网络策略,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | 是 | 计量网络策略 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回设定结果。 |
**示例:**
```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes),
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction};
this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.restoreAllPolicies
restoreAllPolicies(iccid: string, callback: AsyncCallback\<void>): void
重置对应sim卡id的蜂窝网络、后台网络策略、防火墙策略、应用对应的策略,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| iccid | string | 是 | SIM卡ID|
| callback | AsyncCallback\<void> | 是 | 回调函数,返回重置结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam, (error, data) => {
this.callBack(error, data);
});
```
## policy.restoreAllPolicies
restoreAllPolicies(iccid: string): Promise\<void>;
重置对应sim卡id的蜂窝网络、后台网络策略、防火墙策略、应用对应的策略,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| iccid | string | 是 | SIM卡ID|
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam).then(function(error, data){
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.isUidNetAllowed
isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\<boolean>): void
获取对应uid能否访问计量或非计量网络,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
| isMetered | boolean | 是 | 是否为计量网络 |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true表示这个uid可以访问对应的计量网络。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
}
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data);
});
```
## policy.isUidNetAllowed
isUidNetAllowed(uid: number, isMetered: boolean): Promise\<boolean>;
获取对应uid能否访问计量或非计量网络,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
| isMetered | boolean | 是 | 是否为计量网络 |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<boolean> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
}
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.isUidNetAllowed
isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\<boolean>): void
获取对应uid能否访问指定的iface的网络,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
| iface | string | 是 | 网络对应的名称 |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true表示这个uid可以访问对应iface的网络。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam
}
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (error, data) => {
this.callBack(error, data);
});
```
## policy.isUidNetAllowed
isUidNetAllowed(uid: number, iface: string): Promise\<boolean>;
获取对应uid能否访问指定的iface的网络,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
| iface | string | 是 | 网络对应的名称 |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<boolean> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam
}
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setDeviceIdleAllowList
setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\<void>): void
设置指定uid应用是否在休眠防火墙的白名单,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
| isAllowed | boolean | 是 | 是否加入白名单 |
| callback | callback: AsyncCallback\<void> | 是 | 回调函数,返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
}
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data);
});
```
## policy.setDeviceIdleAllowList
setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\<void>;
设置指定uid应用是否在休眠防火墙的白名单,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
| isAllowed | boolean | 是 | 是否加入白名单 |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
}
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getDeviceIdleAllowList
getDeviceIdleAllowList(callback: AsyncCallback\<Array\<number>>): void
获取休眠模式白名单所包含的uid数组,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<Array\<number>> | 是 | 回调函数,返回获取结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getDeviceIdleAllowList((error, data) => {
this.callBack(error, data);
});
```
## policy.getDeviceIdleAllowList
getDeviceIdleAllowList(): Promise\<Array\<number>>;
获取休眠模式白名单所包含的uid数组,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<number>> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getDeviceIdleAllowList().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getBackgroundPolicyByUid
getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\<NetBackgroundPolicy>): void
获取指定uid能否访问后台网络,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
| callback | AsyncCallback\<[NetBackgroundPolicy](#netbackgroundpolicy)> | 是 | 回调函数,返回获取结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => {
this.callBack(error, data);
});
```
## policy.getBackgroundPolicyByUid
getBackgroundPolicyByUid(uid: number): Promise\<NetBackgroundPolicy>;
获取指定uid能否访问后台网络,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetBackgroundPolicy](#netbackgroundpolicy)> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.resetPolicies
resetPolicies(iccid: string, callback: AsyncCallback\<void>): void
重置对应sim卡id的蜂窝网络、后台网络策略、防火墙策略、应用对应的策略,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| iccid | string | 是 | SIM卡ID|
| callback | AsyncCallback\<void> | 是 | 回调函数,返回重置结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
this.firstParam = iccid
policy.resetPolicies(this.firstParam, (error, data) => {
this.callBack(error, data);
});
```
## policy.resetPolicies
resetPolicies(iccid: string): Promise\<void>;
重置对应sim卡id的蜂窝网络、后台网络策略、防火墙策略、应用对应的策略,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| iccid | string | 是 | SIM卡ID|
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) {
})
this.firstParam = iccid
policy.resetPolicies(this.firstParam).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.updateRemindPolicy
updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\<void>): void
更新提醒策略,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | 是 | 网络类型 |
| iccid | string | 是 | SIM卡ID|
| remindType | [RemindType](#remindtype) | 是 | 提醒类型 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回更新结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
}
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (error, data) => {
this.callBack(error, data);
});
```
## policy.updateRemindPolicy
updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): Promise\<void>;
更新提醒策略,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | 是 | 网络类型 |
| iccid | string | 是 | SIM卡ID|
| remindType | [RemindType](#remindtype) | 是 | 提醒类型 |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
}
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setPowerSaveAllowList
setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\<void>): void
设置指定uid应用是否在省电防火墙的白名单,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
| isAllowed | boolean | 是 | 是否加入白名单 |
| callback | callback: AsyncCallback\<void> | 是 | 回调函数,返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
}
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data);
});
```
## policy.setPowerSaveAllowList
setPowerSaveAllowList(uid: number, isAllowed: boolean): Promise\<void>;
设置指定uid应用是否在省电防火墙的白名单,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | 是 | app唯一标识符 |
| isAllowed | boolean | 是 | 是否加入白名单 |
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
}
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getPowerSaveAllowList
getPowerSaveAllowList(callback: AsyncCallback\<Array\<number>>): void
获取省电模式白名单所包含的uid数组,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<Array\<number>> | 是 | 回调函数,返回获取结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getPowerSaveAllowList((error, data) => {
this.callBack(error, data);
});
```
## policy.getPowerSaveAllowList
getPowerSaveAllowList(): Promise\<Array\<number>>;
获取休眠模式白名单所包含的uid数组,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<number>> | 以Promise形式返回设定结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**示例:**
```js
policy.getPowerSaveAllowList().then(function(error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.on
网络策略的句柄。
### on('netUidPolicyChange')
on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void
注册policy发生改变时的回调,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | netUidPolicyChange | 是 | policy发生改变的类型 |
| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy) }> | 是 | 回调函数。注册policy发生改变时调用。 |
**示例:**
```js
policy.on('netUidPolicyChange', (data) => {
this.log('on netUidPolicyChange:' + JSON.stringify(data));
})
```
### on('netUidRuleChange')
on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void
注册rule发生改变时的回调,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | netUidRuleChange | 是 | rule发生改变的类型 |
| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule) }> | 是 | 回调函数。注册rule发生改变时的调用。 |
**示例:**
```js
policy.on('netUidRuleChange', (data) => {
this.log('on netUidRuleChange:' + JSON.stringify(data));
})
```
### on('netMeteredIfacesChange')
on(type: "netMeteredIfacesChange", callback: Callback\<Array\<string>>): void
注册计量iface发生改变时的回调,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | netMeteredIfacesChange | 是 | 计量iface发生改变的类型 |
| callback | Callback\<Array\<string>> | 是 | 回调函数。注册计量iface发生改变时调用。 |
**示例:**
```js
policy.on('netMeteredIfacesChange', (data) => {
this.log('on netMeteredIfacesChange:' + JSON.stringify(data));
})
```
### on('netQuotaPolicyChange')
on(type: "netQuotaPolicyChange", callback: Callback\<Array\<NetQuotaPolicy>>): void
注册计量网络策略发生改变时的回调,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | netQuotaPolicyChange | 是 | 计量网络策略发生改变的类型 |
| callback | Callback\<Array\<[NetQuotaPolicy](#netquotapolicy)>> | 是 | 回调函数。注册计量网络策略发生改变时调用。 |
**示例:**
```js
policy.on('netQuotaPolicyChange', (data) => {
this.log('on netQuotaPolicyChange:' + JSON.stringify(data));
})
```
### on('netBackgroundPolicyChange')
on(type: "netBackgroundPolicyChange", callback: Callback\<boolean>): void
注册后台网络策略发生改变时的回调,使用callback方式作为异步方法。
**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | netBackgroundPolicyChange | 是 | 后台网络策略发生改变的类型 |
| callback | Callback\<boolean> | 是 | 回调函数。注册后台网络策略发生改变时调用。 |
**示例:**
```js
policy.on('netBackgroundPolicyChange', (data) => {
this.log('on netBackgroundPolicyChange:' + JSON.stringify(data));
})
```
## NetBackgroundPolicy
后台网络策略。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 参数名 | 值 | 说明 |
| ------------------------ | ---- | ---------------------- |
| NET_BACKGROUND_POLICY_NONE | 0 | 默认值。 |
| NET_BACKGROUND_POLICY_ENABLE | 1 | 应用在后台可以使用计量网路。 |
| NET_BACKGROUND_POLICY_DISABLE | 2 | 应用在后台不可以使用计量网路。 |
| NET_BACKGROUND_POLICY_ALLOW_LIST | 3 | 只有应用指定的列表在后台可以使用计量网络。 |
## NetQuotaPolicy
计量网络策略。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 参数名 | 类型 | 说明 |
| ----------------------- | ----------------------------------- | ------------------------------------------------------------ |
| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | 网络类型。 |
| iccid | string | 计量蜂窝网络的SIM卡的标识值。以太网,wifi网络不会用到 |
| ident | string | 计量蜂窝网络中配合iccid联合使用。以太网,wifi网络单独使用。用于标记类型。 |
| periodDuration | string | 计量开始时间。 |
| warningBytes | number | 发出警告的流量阈值。 |
| limitBytes | number | 流量设置的配额。 |
| lastWarningRemind | string | 最新一次发出警告的时间。 |
| lastLimitRemind | string | 最新一次配额耗尽的时间。 |
| metered | string | 是否为计量网络。 |
| limitAction | [LimitAction](#limitaction) | 到达流量限制后的动作。 |
## LimitAction
限制动作。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 参数名 | 值 | 说明 |
| ---------------------- | ----- | ------------ |
| LIMIT_ACTION_NONE | -1 | 默认值。 |
| LIMIT_ACTION_DISABLE | 0 | 当配额策略达到限制时,访问被禁用。 |
| LIMIT_ACTION_AUTO_BILL| 1 | 当配额策略达到限制时,用户将自动计费。 |
## NetUidRule
计量网络规则。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 参数名 | 值 | 说明 |
| ---------------------- | ----- | ------------ |
| NET_RULE_NONE | 0 | 默认规则 |
| NET_RULE_ALLOW_METERED_FOREGROUND | 1 | 允许前台访问计量网络 |
| NET_RULE_ALLOW_METERED | 2 | 允许访问计量网络 |
| NET_RULE_REJECT_METERED | 4 | 拒绝访问计量网络 |
| NET_RULE_ALLOW_ALL | 32 | 允许访问所有网络 |
| NET_RULE_REJECT_ALL | 64 | 拒绝访问所有网络 |
## RemindType
提醒类型。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 参数名 | 值 | 说明 |
| ---------------------- | - | ------- |
| REMIND_TYPE_WARNING | 1 | 警告提醒 |
| REMIND_TYPE_LIMIT | 2 | 限制提醒 |
## NetUidPolicy
应用对应的网络策略。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。
| 参数名 | 值 | 说明 |
| ---------------------- | ----- | ------------ |
| NET_POLICY_NONE | 0 | 默认网络策略 |
| NET_POLICY_ALLOW_METERED_BACKGROUND | 1 | 允许应用在后台访问计量网络 |
| NET_POLICY_REJECT_METERED_BACKGROUND | 2 | 拒绝应用在后台访问计量网络 |
# @ohos.net.sharing (网络共享管理) # @ohos.net.sharing (网络共享管理)
网络共享管理分享设备已有网络给其他连接设备,支持Wi-Fi热点共享和蓝牙共享,同时提供网络共享状态、共享流量查询功能。 网络共享管理分享设备已有网络给其他连接设备,支持Wi-Fi热点共享、蓝牙共享和USB共享,同时提供网络共享状态、共享流量查询功能。
> **说明:** > **说明:**
> >
...@@ -30,6 +30,15 @@ isSharingSupported(callback: AsyncCallback\<boolean>): void ...@@ -30,6 +30,15 @@ isSharingSupported(callback: AsyncCallback\<boolean>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true代表支持网络共享。 | | callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true代表支持网络共享。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
...@@ -57,6 +66,15 @@ isSharingSupported(): Promise\<boolean> ...@@ -57,6 +66,15 @@ isSharingSupported(): Promise\<boolean>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<boolean> | 以Promise形式返回是否支持共享结果。 | | Promise\<boolean> | 以Promise形式返回是否支持共享结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
...@@ -85,6 +103,14 @@ isSharing(callback: AsyncCallback\<boolean>): void ...@@ -85,6 +103,14 @@ isSharing(callback: AsyncCallback\<boolean>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true代表网络共享中。 | | callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true代表网络共享中。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -112,6 +138,14 @@ isSharing(): Promise\<boolean> ...@@ -112,6 +138,14 @@ isSharing(): Promise\<boolean>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<boolean> | 以Promise形式返回网络共享状态结果,返回true代表网络共享中。 | | Promise\<boolean> | 以Promise形式返回网络共享状态结果,返回true代表网络共享中。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -141,11 +175,27 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void ...@@ -141,11 +175,27 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void
| type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回开启网络共享结果。 | | callback | AsyncCallback\<void> | 是 | 回调函数,返回开启网络共享结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202004 | Try to share an unavailable iface. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202009 | Network share enable forwarding error. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { let SHARING_WIFI=0;
sharing.startSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -174,11 +224,27 @@ startSharing(type: SharingIfaceType): Promise\<void> ...@@ -174,11 +224,27 @@ startSharing(type: SharingIfaceType): Promise\<void>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回开启共享执行结果。 | | Promise\<void> | 以Promise形式返回开启共享执行结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202004 | Try to share an unavailable iface. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202009 | Network share enable forwarding error. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.startSharing(SharingIfaceType.SHARING_WIFI).then(() => { let SHARING_WIFI=0;
sharing.startSharing(SHARING_WIFI).then(() => {
console.log("start wifi sharing successful"); console.log("start wifi sharing successful");
}).catch(error => { }).catch(error => {
console.log("start wifi sharing failed"); console.log("start wifi sharing failed");
...@@ -204,11 +270,25 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void ...@@ -204,11 +270,25 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void
| type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回停止网络共享结果。 | | callback | AsyncCallback\<void> | 是 | 回调函数,返回停止网络共享结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { let SHARING_WIFI=0;
sharing.stopSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -237,11 +317,25 @@ stopSharing(type: SharingIfaceType): Promise\<void> ...@@ -237,11 +317,25 @@ stopSharing(type: SharingIfaceType): Promise\<void>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回关闭共享执行结果。 | | Promise\<void> | 以Promise形式返回关闭共享执行结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.stopSharing(SharingIfaceType.SHARING_WIFI).then(() => { let SHARING_WIFI=0;
sharing.stopSharing(SHARING_WIFI).then(() => {
console.log("stop wifi sharing successful"); console.log("stop wifi sharing successful");
}).catch(error => { }).catch(error => {
console.log("stop wifi sharing failed"); console.log("stop wifi sharing failed");
...@@ -266,6 +360,14 @@ getStatsRxBytes(callback: AsyncCallback\<number>): void ...@@ -266,6 +360,14 @@ getStatsRxBytes(callback: AsyncCallback\<number>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 | | callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -293,6 +395,14 @@ getStatsRxBytes(): Promise\<number> ...@@ -293,6 +395,14 @@ getStatsRxBytes(): Promise\<number>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<number> | 以Promise形式返回共享网络接收数据量,单位:KB。 | | Promise\<number> | 以Promise形式返回共享网络接收数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -321,6 +431,14 @@ getStatsTxBytes(callback: AsyncCallback\<number>): void ...@@ -321,6 +431,14 @@ getStatsTxBytes(callback: AsyncCallback\<number>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 | | callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -348,6 +466,14 @@ getStatsTxBytes(): Promise\<number> ...@@ -348,6 +466,14 @@ getStatsTxBytes(): Promise\<number>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<number> | 以Promise形式返回共享网络发送数据量,单位:KB。 | | Promise\<number> | 以Promise形式返回共享网络发送数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -376,6 +502,14 @@ getStatsTotalBytes(callback: AsyncCallback\<number>): void ...@@ -376,6 +502,14 @@ getStatsTotalBytes(callback: AsyncCallback\<number>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 | | callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -403,6 +537,14 @@ getStatsTotalBytes(): Promise\<number> ...@@ -403,6 +537,14 @@ getStatsTotalBytes(): Promise\<number>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<number> | 以Promise形式返回共享网络总数据量,单位:KB。 | | Promise\<number> | 以Promise形式返回共享网络总数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -432,11 +574,22 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<strin ...@@ -432,11 +574,22 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<strin
| state | [SharingIfaceState](#sharingifacestate) | 是 | 网络共享状态。 | | state | [SharingIfaceState](#sharingifacestate) | 是 | 网络共享状态。 |
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回指定状态的网卡名称列表。 | | callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回指定状态的网卡名称列表。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { let SHARING_BLUETOOTH=2;
sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
...@@ -466,11 +619,22 @@ getSharingIfaces(state: SharingIfaceState): Promise\<Array\<string>> ...@@ -466,11 +619,22 @@ getSharingIfaces(state: SharingIfaceState): Promise\<Array\<string>>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<Array\<string>> | 以Promise形式返回指定状态网卡名称列表。 | | Promise\<Array\<string>> | 以Promise形式返回指定状态网卡名称列表。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER).then(data => { let SHARING_BLUETOOTH=2;
sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
...@@ -496,11 +660,22 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceSta ...@@ -496,11 +660,22 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceSta
| type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 |
| callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | 是 | 回调函数,返回指定类型网络共享状态。 | | callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | 是 | 回调函数,返回指定类型网络共享状态。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { let SHARING_WIFI=0;
sharing.getSharingState(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
...@@ -524,6 +699,16 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState> ...@@ -524,6 +699,16 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState>
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
...@@ -534,7 +719,8 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState> ...@@ -534,7 +719,8 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState>
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharingState(SharingIfaceType.SHARING_WIFI).then(data => { let SHARING_WIFI=0;
sharing.getSharingState(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
...@@ -560,11 +746,22 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<strin ...@@ -560,11 +746,22 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<strin
| type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 |
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回指定类型网卡名称正则表达式列表。 | | callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回指定类型网卡名称正则表达式列表。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI, (error, data) => { let SHARING_WIFI=0;
sharing.getSharableRegexes(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
...@@ -594,11 +791,22 @@ getSharableRegexes(type: SharingIfaceType): Promise\<Array\<string>> ...@@ -594,11 +791,22 @@ getSharableRegexes(type: SharingIfaceType): Promise\<Array\<string>>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<Array\<string>> | 以Promise形式返回正则表达式列表。 | | Promise\<Array\<string>> | 以Promise形式返回正则表达式列表。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => { let SHARING_WIFI=0;
sharing.getSharableRegexes(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
...@@ -624,12 +832,18 @@ on(type: 'sharingStateChange', callback: Callback\<boolean>): void ...@@ -624,12 +832,18 @@ on(type: 'sharingStateChange', callback: Callback\<boolean>): void
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,返回网络共享状态。 | | callback | AsyncCallback\<boolean> | 是 | 回调函数,返回网络共享状态。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
sharing.on('sharingStateChange', (error, data) => { sharing.on('sharingStateChange', (data) => {
console.log(JSON.stringify(error)); console.log('on sharingStateChange:' + JSON.stringify(data));
console.log(JSON.stringify(data));
}); });
``` ```
...@@ -652,11 +866,17 @@ off(type: 'sharingStateChange', callback?: Callback\<boolean>): void ...@@ -652,11 +866,17 @@ off(type: 'sharingStateChange', callback?: Callback\<boolean>): void
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<boolean> | 否 | 回调函数,返回网络共享状态。 | | callback | AsyncCallback\<boolean> | 否 | 回调函数,返回网络共享状态。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
sharing.off('sharingStateChange', (error, data) => { sharing.off('sharingStateChange', (data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -680,12 +900,18 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface ...@@ -680,12 +900,18 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | 是 | 回调函数,指定网卡共享状态变化时调用。 | | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | 是 | 回调函数,指定网卡共享状态变化时调用。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
sharing.on('interfaceSharingStateChange', (error, data) => { sharing.on('interfaceSharingStateChange', (data) => {
console.log(JSON.stringify(error)); console.log('on interfaceSharingStateChange:' + JSON.stringify(data));
console.log(JSON.stringify(data));
}); });
``` ```
...@@ -708,11 +934,17 @@ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfa ...@@ -708,11 +934,17 @@ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfa
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | 否 | 回调函数,注销指定网卡共享状态变化通知。 | | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | 否 | 回调函数,注销指定网卡共享状态变化通知。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
sharing.off('interfaceSharingStateChange', (error, data) => { sharing.off('interfaceSharingStateChange', (data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -736,12 +968,18 @@ on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void ...@@ -736,12 +968,18 @@ on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<NetHandle> | 是 | 回调函数,上行网络变化时调用。 | | callback | AsyncCallback\<NetHandle> | 是 | 回调函数,上行网络变化时调用。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
sharing.on('sharingUpstreamChange', (error, data) => { sharing.on('sharingUpstreamChange', (data) => {
console.log(JSON.stringify(error)); console.log('on sharingUpstreamChange:' + JSON.stringify(data));
console.log(JSON.stringify(data));
}); });
``` ```
...@@ -764,11 +1002,17 @@ off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void ...@@ -764,11 +1002,17 @@ off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<NetHandle> | 否 | 回调函数,注销上行网络变化事件。 | | callback | AsyncCallback\<NetHandle> | 否 | 回调函数,注销上行网络变化事件。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
sharing.off('sharingUpstreamChange', (error, data) => { sharing.off('sharingUpstreamChange', (data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -789,7 +1033,7 @@ sharing.off('sharingUpstreamChange', (error, data) => { ...@@ -789,7 +1033,7 @@ sharing.off('sharingUpstreamChange', (error, data) => {
## SharingIfaceType ## SharingIfaceType
网络共享类型(暂不支持USB共享) 网络共享类型。
**系统接口**:此接口为系统接口。 **系统接口**:此接口为系统接口。
......
...@@ -53,6 +53,13 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void ...@@ -53,6 +53,13 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 | | address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 | | callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -83,6 +90,12 @@ bind\(address: NetAddress\): Promise<void\> ...@@ -83,6 +90,12 @@ bind\(address: NetAddress\): Promise<void\>
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | | ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 | | address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**返回值:** **返回值:**
...@@ -122,6 +135,13 @@ send\(options: UDPSendOptions, callback: AsyncCallback<void\>\): void ...@@ -122,6 +135,13 @@ send\(options: UDPSendOptions, callback: AsyncCallback<void\>\): void
| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 | | options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 | | callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -161,6 +181,13 @@ send\(options: UDPSendOptions\): Promise<void\> ...@@ -161,6 +181,13 @@ send\(options: UDPSendOptions\): Promise<void\>
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 | | options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
...@@ -265,6 +292,12 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void ...@@ -265,6 +292,12 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void
| -------- | ------------------------------------------------------ | ---- | ---------- | | -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 | | callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -345,6 +378,12 @@ setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback<void\>\): voi ...@@ -345,6 +378,12 @@ setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback<void\>\): voi
| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 | | options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 | | callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
...@@ -398,6 +437,13 @@ setExtraOptions\(options: UDPExtraOptions\): Promise<void\> ...@@ -398,6 +437,13 @@ setExtraOptions\(options: UDPExtraOptions\): Promise<void\>
| :-------------- | :--------------------------------------------------- | | :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置UDPSocket连接的其他属性的结果。 | | Promise\<void\> | 以Promise形式返回设置UDPSocket连接的其他属性的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -562,7 +608,6 @@ on\(type: 'error', callback: ErrorCallback\): void ...@@ -562,7 +608,6 @@ on\(type: 'error', callback: ErrorCallback\): void
| type | string | 是 | 订阅的事件类型。'error':error事件。 | | type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 | | callback | ErrorCallback | 是 | 回调函数。 |
**示例:** **示例:**
```js ```js
...@@ -667,6 +712,12 @@ Socket的连接信息。 ...@@ -667,6 +712,12 @@ Socket的连接信息。
| port | number | 是 | 端口号,范围0~65535。 | | port | number | 是 | 端口号,范围0~65535。 |
| size | number | 是 | 服务器响应信息的字节长度。 | | size | number | 是 | 服务器响应信息的字节长度。 |
## UDP 错误码说明
UDP 其余错误码映射形式为:2301000 + Linux内核错误码。
错误码的详细介绍参见[Socket错误码](../errorcodes/errorcode-net-socket.md)
## socket.constructTCPSocketInstance ## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket constructTCPSocketInstance\(\): TCPSocket
...@@ -709,6 +760,12 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void ...@@ -709,6 +760,12 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 | | address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 | | callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
...@@ -746,6 +803,13 @@ bind\(address: NetAddress\): Promise<void\> ...@@ -746,6 +803,13 @@ bind\(address: NetAddress\): Promise<void\>
| :-------------- | :------------------------------------------------------- | | :-------------- | :------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TCPSocket绑定本机的IP地址和端口的结果。 | | Promise\<void\> | 以Promise形式返回TCPSocket绑定本机的IP地址和端口的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -776,6 +840,13 @@ connect\(options: TCPConnectOptions, callback: AsyncCallback<void\>\): void ...@@ -776,6 +840,13 @@ connect\(options: TCPConnectOptions, callback: AsyncCallback<void\>\): void
| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 | | options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 | | callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -812,6 +883,13 @@ connect\(options: TCPConnectOptions\): Promise<void\> ...@@ -812,6 +883,13 @@ connect\(options: TCPConnectOptions\): Promise<void\>
| :-------------- | :--------------------------------------------------------- | | :-------------- | :--------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TCPSocket连接到指定的IP地址和端口的结果。 | | Promise\<void\> | 以Promise形式返回TCPSocket连接到指定的IP地址和端口的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -845,6 +923,13 @@ send\(options: TCPSendOptions, callback: AsyncCallback<void\>\): void ...@@ -845,6 +923,13 @@ send\(options: TCPSendOptions, callback: AsyncCallback<void\>\): void
| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 | | options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 | | callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -892,6 +977,13 @@ send\(options: TCPSendOptions\): Promise<void\> ...@@ -892,6 +977,13 @@ send\(options: TCPSendOptions\): Promise<void\>
| :-------------- | :------------------------------------------------- | | :-------------- | :------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回通过TCPSocket连接发送数据的结果。 | | Promise\<void\> | 以Promise形式返回通过TCPSocket连接发送数据的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -929,6 +1021,11 @@ close\(callback: AsyncCallback<void\>\): void ...@@ -929,6 +1021,11 @@ close\(callback: AsyncCallback<void\>\): void
| -------- | --------------------- | ---- | ---------- | | -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 | | callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 201 | Permission denied. |
**示例:** **示例:**
...@@ -960,6 +1057,12 @@ close\(\): Promise<void\> ...@@ -960,6 +1057,12 @@ close\(\): Promise<void\>
| :-------------- | :----------------------------------------- | | :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式返回关闭TCPSocket连接的结果。 | | Promise\<void\> | 以Promise形式返回关闭TCPSocket连接的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -992,6 +1095,12 @@ getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void ...@@ -992,6 +1095,12 @@ getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
| -------- | ------------------------------------------------- | ---- | ---------- | | -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback<[NetAddress](#netaddress)> | 是 | 回调函数。 | | callback | AsyncCallback<[NetAddress](#netaddress)> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -1031,6 +1140,12 @@ getRemoteAddress\(\): Promise<NetAddress\> ...@@ -1031,6 +1140,12 @@ getRemoteAddress\(\): Promise<NetAddress\>
| :------------------------------------------ | :------------------------------------------ | | :------------------------------------------ | :------------------------------------------ |
| Promise<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。 | | Promise<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -1069,6 +1184,11 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void ...@@ -1069,6 +1184,11 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void
| -------- | ------------------------------------------------------ | ---- | ---------- | | -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 | | callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 201 | Permission denied. |
**示例:** **示例:**
...@@ -1109,6 +1229,11 @@ getState\(\): Promise<SocketStateBase\> ...@@ -1109,6 +1229,11 @@ getState\(\): Promise<SocketStateBase\>
| :----------------------------------------------- | :----------------------------------------- | | :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TCPSocket状态的结果。 | | Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TCPSocket状态的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 201 | Permission denied. |
**示例:** **示例:**
...@@ -1149,6 +1274,13 @@ setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): voi ...@@ -1149,6 +1274,13 @@ setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): voi
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 | | options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 | | callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -1203,6 +1335,12 @@ setExtraOptions\(options: TCPExtraOptions\): Promise<void\> ...@@ -1203,6 +1335,12 @@ setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
| :-------------- | :--------------------------------------------------- | | :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。 | | Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
...@@ -1304,7 +1442,6 @@ on\(type: 'connect' | 'close', callback: Callback<void\>\): void ...@@ -1304,7 +1442,6 @@ on\(type: 'connect' | 'close', callback: Callback<void\>\): void
| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 | | type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 是 | 回调函数。 | | callback | Callback\<void\> | 是 | 回调函数。 |
**示例:** **示例:**
```js ```js
...@@ -1453,6 +1590,12 @@ TCPSocket连接的其他属性。 ...@@ -1453,6 +1590,12 @@ TCPSocket连接的其他属性。
| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 | | reuseAddress | boolean | 否 | 是否重用地址。默认为false。 |
| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 | | socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 |
## TCP 错误码说明
TCP 其余错误码映射形式为:2301000 + Linux内核错误码。
错误码的详细介绍参见[Socket错误码](../errorcodes/errorcode-net-socket.md)
## socket.constructTLSSocketInstance<sup>9+</sup> ## socket.constructTLSSocketInstance<sup>9+</sup>
constructTLSSocketInstance(): TLSSocket constructTLSSocketInstance(): TLSSocket
...@@ -1766,7 +1909,6 @@ connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void ...@@ -1766,7 +1909,6 @@ connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void
| 2303104 | Interrupted system call. | | 2303104 | Interrupted system call. |
| 2303109 | Bad file number. | | 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. | | 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. | | 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. | | 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. | | 2303198 | Address already in use. |
...@@ -1783,7 +1925,7 @@ connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void ...@@ -1783,7 +1925,7 @@ connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void
```js ```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
...@@ -1794,14 +1936,14 @@ let options = { ...@@ -1794,14 +1936,14 @@ let options = {
ALPNProtocols: ["spdy/1", "http/1.1"], ALPNProtocols: ["spdy/1", "http/1.1"],
address: { address: {
address: "192.168.xx.xxx", address: "192.168.xx.xxx",
port: xxxx, port: 8080,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
key: "xxxx", key: "xxxx",
cert: "xxxx", cert: "xxxx",
ca: ["xxxx"], ca: ["xxxx"],
passwd: "xxxx", password: "xxxx",
protocols: [socket.Protocol.TLSv12], protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true, useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
...@@ -1809,12 +1951,12 @@ let options = { ...@@ -1809,12 +1951,12 @@ let options = {
}, },
}; };
tlsTwoWay.connect(options, (err, data) => { tlsTwoWay.connect(options, (err, data) => {
console.error(err); console.error("connect callback error"+err);
console.log(data); console.log(JSON.stringify(data));
}); });
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
...@@ -1824,7 +1966,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { ...@@ -1824,7 +1966,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
let oneWayOptions = { let oneWayOptions = {
address: { address: {
address: "192.168.xxx.xxx", address: "192.168.xxx.xxx",
port: xxxx, port: 8080,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
...@@ -1833,8 +1975,8 @@ let oneWayOptions = { ...@@ -1833,8 +1975,8 @@ let oneWayOptions = {
}, },
}; };
tlsOneWay.connect(oneWayOptions, (err, data) => { tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err); console.error("connect callback error"+err);
console.log(data); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -1866,7 +2008,6 @@ connect(options: TLSConnectOptions): Promise\<void> ...@@ -1866,7 +2008,6 @@ connect(options: TLSConnectOptions): Promise\<void>
| 2303104 | Interrupted system call. | | 2303104 | Interrupted system call. |
| 2303109 | Bad file number. | | 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. | | 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. | | 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. | | 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. | | 2303198 | Address already in use. |
...@@ -1883,7 +2024,7 @@ connect(options: TLSConnectOptions): Promise\<void> ...@@ -1883,7 +2024,7 @@ connect(options: TLSConnectOptions): Promise\<void>
```js ```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
...@@ -1894,14 +2035,14 @@ let options = { ...@@ -1894,14 +2035,14 @@ let options = {
ALPNProtocols: ["spdy/1", "http/1.1"], ALPNProtocols: ["spdy/1", "http/1.1"],
address: { address: {
address: "xxxx", address: "xxxx",
port: xxxx, port: 8080,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
key: "xxxx", key: "xxxx",
cert: "xxxx", cert: "xxxx",
ca: ["xxxx"], ca: ["xxxx"],
passwd: "xxxx", password: "xxxx",
protocols: [socket.Protocol.TLSv12], protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true, useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
...@@ -1909,13 +2050,13 @@ let options = { ...@@ -1909,13 +2050,13 @@ let options = {
}, },
}; };
tlsTwoWay.connect(options).then(data => { tlsTwoWay.connect(options).then(data => {
console.log(data); console.log(JSON.stringify(data));
}).catch(err => { }).catch(err => {
console.error(err); console.error(err);
}); });
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
...@@ -1925,7 +2066,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { ...@@ -1925,7 +2066,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
let oneWayOptions = { let oneWayOptions = {
address: { address: {
address: "192.168.xxx.xxx", address: "192.168.xxx.xxx",
port: xxxx, port: 8080,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
...@@ -1934,7 +2075,7 @@ let oneWayOptions = { ...@@ -1934,7 +2075,7 @@ let oneWayOptions = {
}, },
}; };
tlsOneWay.connect(oneWayOptions).then(data => { tlsOneWay.connect(oneWayOptions).then(data => {
console.log(data); console.log(JSON.stringify(data));
}).catch(err => { }).catch(err => {
console.error(err); console.error(err);
}); });
...@@ -2263,7 +2404,7 @@ getCipherSuite(): Promise\<Array\<string>> ...@@ -2263,7 +2404,7 @@ getCipherSuite(): Promise\<Array\<string>>
```js ```js
tls.getCipherSuite().then(data => { tls.getCipherSuite().then(data => {
console.log(data); console.log('getCipherSuite success:' + JSON.stringify(data));
}).catch(err => { }).catch(err => {
console.error(err); console.error(err);
}); });
...@@ -2327,7 +2468,7 @@ getSignatureAlgorithms(): Promise\<Array\<string>> ...@@ -2327,7 +2468,7 @@ getSignatureAlgorithms(): Promise\<Array\<string>>
```js ```js
tls.getSignatureAlgorithms().then(data => { tls.getSignatureAlgorithms().then(data => {
console.log(data); console.log("getSignatureAlgorithms success" + data);
}).catch(err => { }).catch(err => {
console.error(err); console.error(err);
}); });
...@@ -2503,7 +2644,7 @@ TLS安全相关操作,其中ca证书为必选参数,其他参数为可选参 ...@@ -2503,7 +2644,7 @@ TLS安全相关操作,其中ca证书为必选参数,其他参数为可选参
| ca | string \| Array\<string> | 是 | 服务端的ca证书,用于认证校验服务端的数字证书。| | ca | string \| Array\<string> | 是 | 服务端的ca证书,用于认证校验服务端的数字证书。|
| cert | string | 否 | 本地客户端的数字证书。 | | cert | string | 否 | 本地客户端的数字证书。 |
| key | string | 否 | 本地数字证书的私钥。 | | key | string | 否 | 本地数字证书的私钥。 |
| passwd | string | 否 | 读取私钥的密码。 | | password | string | 否 | 读取私钥的密码。 |
| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | 否 | TLS的协议版本。 | | protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | 否 | TLS的协议版本。 |
| useRemoteCipherPrefer | boolean | 否 | 优先使用对等方的密码套件。 | | useRemoteCipherPrefer | boolean | 否 | 优先使用对等方的密码套件。 |
| signatureAlgorithms | string | 否 | 通信过程中的签名算法。 | | signatureAlgorithms | string | 否 | 通信过程中的签名算法。 |
...@@ -2528,4 +2669,4 @@ TLS通信的协议版本。 ...@@ -2528,4 +2669,4 @@ TLS通信的协议版本。
| 类型 | 说明 | | 类型 | 说明 |
| --------------------------------------------------------------------- | --------------------- | | --------------------------------------------------------------------- | --------------------- |
|[cryptoFramework.EncodingBlob](js-apis-cryptoFramework.md#datablob) | 存储证书的数据和编码格式 | |[cryptoFramework.EncodingBlob](js-apis-cryptoFramework.md#datablob) | 存储证书的数据和编码格式 |
\ No newline at end of file
...@@ -45,11 +45,11 @@ fetch(Object): void ...@@ -45,11 +45,11 @@ fetch(Object): void
## FetchResponse ## FetchResponse
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| code | number | 表示服务器的状态code。 | | code | number | 是 | 否 | 表示服务器的状态code。 |
| data | string \| Object | 返回数据类型由responseType确定,详见表 responseType与success中data关系。 | | data | string \| Object | 是 | 否 | 返回数据类型由responseType确定,详见表 responseType与success中data关系。 |
| headers | Object | 表示服务器response的所有header。 | | headers | Object | 是 | 否 | 表示服务器response的所有header。 |
**表2** responseType与success中data关系 **表2** responseType与success中data关系
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
> **说明:** > **说明:**
> - 从API Version 7 开始,该接口不再维护,推荐使用新接口[`@ohos.telephony.observer`](js-apis-observer.md)。 > - 从API Version 7 开始,该接口不再维护,推荐使用新接口[`@ohos.telephony.observer`](js-apis-observer.md)。
> >
> - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -122,7 +122,9 @@ export default { ...@@ -122,7 +122,9 @@ export default {
## NetworkResponse ## NetworkResponse
| 参数名 | 类型 | 说明 | **系统能力:** SystemCapability.Communication.NetManager.Core
| -------- | -------- | -------- |
| metered | boolean | 是否按照流量计费。 | | 参数名 | 类型 | 必填 | 说明 |
| type | string | 网络类型,可能的值有2g,3g,4g,5g,wifi,none等。 | | -------- | -------- | -------- | -------- |
\ No newline at end of file | metered | boolean | 否 |是否按照流量计费。 |
| type | string | 是|网络类型,可能的值有2g,3g,4g,5g,wifi,none等。 |
\ No newline at end of file
...@@ -104,6 +104,12 @@ connect\(url: string, callback: AsyncCallback<boolean\>\): void ...@@ -104,6 +104,12 @@ connect\(url: string, callback: AsyncCallback<boolean\>\): void
| url | string | 是 | 建立WebSocket连接的URL地址。 | | url | string | 是 | 建立WebSocket连接的URL地址。 |
| callback | AsyncCallback\<boolean\> | 是 | 回调函数。 | | callback | AsyncCallback\<boolean\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
...@@ -138,6 +144,12 @@ connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback< ...@@ -138,6 +144,12 @@ connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback<
| options | WebSocketRequestOptions | 是 | 参考[WebSocketRequestOptions](#websocketrequestoptions)。 | | options | WebSocketRequestOptions | 是 | 参考[WebSocketRequestOptions](#websocketrequestoptions)。 |
| callback | AsyncCallback\<boolean\> | 是 | 回调函数。 | | callback | AsyncCallback\<boolean\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
...@@ -182,6 +194,13 @@ connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\> ...@@ -182,6 +194,13 @@ connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\>
| :----------------- | :-------------------------------- | | :----------------- | :-------------------------------- |
| Promise\<boolean\> | 以Promise形式返回建立连接的结果。 | | Promise\<boolean\> | 以Promise形式返回建立连接的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -213,6 +232,13 @@ send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void ...@@ -213,6 +232,13 @@ send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void
| data | string \| ArrayBuffer <sup>8+</sup> | 是 | 发送的数据。 | | data | string \| ArrayBuffer <sup>8+</sup> | 是 | 发送的数据。 |
| callback | AsyncCallback\<boolean\> | 是 | 回调函数。 | | callback | AsyncCallback\<boolean\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -252,6 +278,13 @@ send\(data: string | ArrayBuffer\): Promise<boolean\> ...@@ -252,6 +278,13 @@ send\(data: string | ArrayBuffer\): Promise<boolean\>
| :----------------- | :-------------------------------- | | :----------------- | :-------------------------------- |
| Promise\<boolean\> | 以Promise形式返回发送数据的结果。 | | Promise\<boolean\> | 以Promise形式返回发送数据的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -284,6 +317,13 @@ close\(callback: AsyncCallback<boolean\>\): void ...@@ -284,6 +317,13 @@ close\(callback: AsyncCallback<boolean\>\): void
| -------- | ------------------------ | ---- | ---------- | | -------- | ------------------------ | ---- | ---------- |
| callback | AsyncCallback\<boolean\> | 是 | 回调函数。 | | callback | AsyncCallback\<boolean\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -316,6 +356,13 @@ close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void ...@@ -316,6 +356,13 @@ close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void
| options | WebSocketCloseOptions | 是 | 参考[WebSocketCloseOptions](#websocketcloseoptions)。 | | options | WebSocketCloseOptions | 是 | 参考[WebSocketCloseOptions](#websocketcloseoptions)。 |
| callback | AsyncCallback\<boolean\> | 是 | 回调函数。 | | callback | AsyncCallback\<boolean\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -356,6 +403,13 @@ close\(options?: WebSocketCloseOptions\): Promise<boolean\> ...@@ -356,6 +403,13 @@ close\(options?: WebSocketCloseOptions\): Promise<boolean\>
| :----------------- | :-------------------------------- | | :----------------- | :-------------------------------- |
| Promise\<boolean\> | 以Promise形式返回关闭连接的结果。 | | Promise\<boolean\> | 以Promise形式返回关闭连接的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**示例:** **示例:**
```js ```js
...@@ -448,7 +502,6 @@ on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void ...@@ -448,7 +502,6 @@ on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void
| type | string | 是 | 'message':WebSocket的接收到服务器消息事件。 | | type | string | 是 | 'message':WebSocket的接收到服务器消息事件。 |
| callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | 是 | 回调函数。 | | callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | 是 | 回调函数。 |
**示例:** **示例:**
```js ```js
...@@ -529,7 +582,6 @@ off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\ ...@@ -529,7 +582,6 @@ off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\
| type | string | 是 | 'close':WebSocket的关闭事件。 | | type | string | 是 | 'close':WebSocket的关闭事件。 |
| callback | AsyncCallback<{ code: number, reason: string }> | 否 | 回调函数。 | | callback | AsyncCallback<{ code: number, reason: string }> | 否 | 回调函数。 |
**示例:** **示例:**
```js ```js
...@@ -553,7 +605,6 @@ on\(type: 'error', callback: ErrorCallback\): void ...@@ -553,7 +605,6 @@ on\(type: 'error', callback: ErrorCallback\): void
| type | string | 是 | 'error':WebSocket的Error事件。 | | type | string | 是 | 'error':WebSocket的Error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 | | callback | ErrorCallback | 是 | 回调函数。 |
**示例:** **示例:**
```js ```js
......
...@@ -49,6 +49,12 @@ ...@@ -49,6 +49,12 @@
- [电话子系统错误码](errorcode-telephony.md) - [电话子系统错误码](errorcode-telephony.md)
- 网络管理 - 网络管理
- [上传下载错误码](errorcode-request.md) - [上传下载错误码](errorcode-request.md)
- [HTTP错误码](errorcode-net-http.md)
- [Socket错误码](errorcode-net-socket.md)
- [网络连接管理错误码](errorcode-net-connection.md)
- [以太网连接错误码](errorcode-net-ethernet.md)
- [网络共享错误码](errorcode-net-sharing.md)
- [策略管理错误码](errorcode-net-policy.md)
- 通信与连接 - 通信与连接
- [NFC错误码](errorcode-nfc.md) - [NFC错误码](errorcode-nfc.md)
- [RPC错误码](errorcode-rpc.md) - [RPC错误码](errorcode-rpc.md)
......
# 网络连接管理错误码
## 2100001 非法参数值
**错误信息**
Invalid parameter value.
**错误描述**
非法参数值。
**可能原因**
输入参数取值范围错误。
**处理步骤**
检查输入参数的取值范围是否正确。
## 2100002 连接服务失败
**错误信息**
Operation failed. Cannot connect to service.
**错误描述**
操作失败,连接系统服务发生异常。
**可能原因**
服务发生异常。
**处理步骤**
检查系统服务运行状态是否正常。
## 2100003 系统内部错误
**错误信息**
System internal error.
**错误描述**
系统内部错误。
**可能原因**
1.内存异常。
2.空指针。
**处理步骤**
1.检查内存空间是否充足,清理内存后重试。
2.系统异常,请稍后重试或重启设备。
## 2101007 已存在相同的callback
**错误信息**
The same callback exists.
**错误描述**
已经注册的callback。
**可能原因**
激活&监听指定属性网络并注册回调时,callback对象重复注册。
**处理步骤**
1.确保待注册的callback对象未进行过注册
2.若callback对象已进行过注册,执行已存在的注册。
## 2101008 callback不存在
**错误信息**
The callback is not exists.
**错误描述**
不存在的callback对象。
**可能原因**
未执行激活&监听指定属性网络请求并注册回调。
**处理步骤**
检查callback对象,确保注销callback对象前,已执行注册函数。
## 2101022 请求数量超过最大值
**错误信息**
The number of requests exceeded the maximum.
**错误描述**
网络请求数超过了最大值。
**可能原因**
激活&监听指定属性网络请求数超过了最大值。
**处理步骤**
建议通过日志信息“Over the max request number”定位问题。
# 以太网错误码
## 2200001 非法参数值
**错误信息**
Invalid parameter value.
**错误描述**
非法参数值。
**可能原因**
输入参数取值范围错误。
**处理步骤**
检查输入参数的取值范围是否正确。
## 2200002 连接服务失败
**错误信息**
Operation failed. Cannot connect to service.
**错误描述**
操作失败,连接系统服务发生异常。
**可能原因**
服务发生异常。
**处理步骤**
检查系统服务运行状态是否正常。
## 2200003 系统内部错误
**错误信息**
System internal error.
**错误描述**
系统内部错误。
**可能原因**
1.内存异常。
2.空指针。
**处理步骤**
1.检查内存空间是否充足,清理内存后重试。
2.系统异常,请稍后重试或重启设备。
## 2201005 设备信息不存在
**错误信息**
The device information does not exist.
**错误描述**
设备信息不存在。
**可能原因**
设置的设备或者获取的设备不存在。
**处理步骤**
```bash
> hdc shell ifconfig
```
查看是否有对应的设备,比如eth0,eth1。
## 2201006 设备未连接
**错误信息**
Device disconnected.
**错误描述**
设备未连接。
**可能原因**
硬件网卡问题。
**处理步骤**
需要查看以太网服务和底层netsys的log,查看kernel是否有上报连接状态。
## 2201007 用户配置写入失败
**错误信息**
Failed to write the user configuration.
**错误描述**
写入配置文件信息失败。
**可能原因**
系统报错。
**处理步骤**
系统内部错误,出现的情况不明确,建议通过日志定位问题。
# HTTP错误码
## 2300001 不支持的协议
**错误信息**
Unsupported protocol.
**错误描述**
协议版本服务器不支持。
**可能原因**
传入的协议版本,服务器不支持。
**处理步骤**
请检查传入的协议版本是否合理,排查服务器实现。
## 2300003 URL格式错误
**错误信息**
URL using bad/illegal format or missing URL.
**错误描述**
URL格式错误。
**可能原因**
可能传入的url格式不正确。
**处理步骤**
检查传入的url格式是否正确。
## 2300005 代理服务器域名解析失败
**错误信息**
Couldn't resolve proxy name.
**错误描述**
代理服务器的域名无法解析。
**可能原因**
服务器的URL不正确
**处理步骤**
排查代理服务器的URL是否正确。
## 2300006 域名解析失败
**错误信息**
Couldn't resolve host name.
**错误描述**
服务器的域名无法解析。
**可能原因**
1.传入的服务器的URL不正确。
2.网络不通畅。
**处理步骤**
1.请检查输入的服务器的URL是否合理。
2.请检查网络连接情况
## 2300007 无法连接到服务器
**错误信息**
Couldn't connect to server.
**错误描述**
服务器无法连接。
**可能原因**
可能传入的url格式不正确。
**处理步骤**
检查传入的url格式是否正确。
## 2300008 服务器返回非法数据
**错误信息**
Weird server reply.
**错误描述**
服务器返回非法数据。
**可能原因**
服务器出错,返回了非HTTP格式的数据。
**处理步骤**
排查服务器实现。
## 2300009 拒绝对远程资源的访问
**错误信息**
Access denied to remote resource.
**错误描述**
拒绝对远程资源的访问。
**可能原因**
指定的内容被服务器拒绝访问。
**处理步骤**
排查请求内容。
## 2300016 HTT2帧层错误
**错误信息**
Error in the HTTP2 framing layer.
**错误描述**
HTTP2层级的错误。
**可能原因**
服务器不支持HTTP2。
**处理步骤**
抓包分析、排查服务器是否支持HTTP2。
## 2300018 服务器返回数据不完整
**错误信息**
Transferred a partial file.
**错误描述**
服务器返回的数据不完整。
**可能原因**
可能与服务器实现有关
**处理步骤**
排查服务器实现。
## 2300023 向磁盘/应用程序写入接收数据失败
**错误信息**
Failed writing received data to disk/application.
**错误描述**
向磁盘/应用程序写入接收数据失败。
**可能原因**
应用没有写文件权限。
**处理步骤**
排查应用权限。
## 2300025 上传失败
**错误信息**
Upload failed.
**错误描述**
上传失败。
**可能原因**
文件过大或者网络问题。对于FTP,服务器通常会拒绝STOR命令。错误缓冲区通常包含服务器的解释。
**处理步骤**
排查文件大小及网络状况。
## 2300026 从文件/应用程序中打开/读取本地数据失败
**错误信息**
Failed to open/read local data from file/application.
**错误描述**
从文件/应用程序中打开/读取本地数据失败。
**可能原因**
应用没有读文件权限
**处理步骤**
排查应用权限。
## 2300027 内存不足
**错误信息**
Out of memory.
**错误描述**
内存不足。
**可能原因**
内存不足。
**处理步骤**
排查系统内存。
## 2300028 操作超时
**错误信息**
Timeout was reached.
**错误描述**
操作超时。
**可能原因**
TCP连接超时或读写超时。
**处理步骤**
排查网络问题。
## 2300047 重定向次数达到最大值
**错误信息**
Number of redirects hit maximum amount.
**错误描述**
重定向次数达到最大值。
**可能原因**
重定向次数过多
**处理步骤**
排查服务器实现。
## 2300052 服务器没有返回内容
**错误信息**
Server returned nothing (no headers, no data).
**错误描述**
服务器没有返回内容。
**可能原因**
可能与服务器实现有关。
**处理步骤**
排查服务器实现。
## 2300055 发送网络数据失败
**错误信息**
Failed sending data to the peer.
**错误描述**
无法往对端发送数据,发送网络数据失败。
**可能原因**
网络问题。
**处理步骤**
排查网络。
## 2300056 接收网络数据失败
**错误信息**
Failure when receiving data from the peer.
**错误描述**
无法往从对端收到数据,接收网络数据失败。
**可能原因**
网络问题
**处理步骤**
排查网络问题。
## 2300058 本地SSL证书错误
**错误信息**
Problem with the local SSL certificate.
**错误描述**
本地SSL证书错误。
**可能原因**
SSL证书格式有错误。
**处理步骤**
检查SSL证书格式。
## 2300059 无法使用指定的密码
**错误信息**
Couldn't use specified SSL cipher.
**错误描述**
无法使用指定的密码。
**可能原因**
client和sever协商的加密算法系统不支持。
**处理步骤**
抓包分析协商的算法。
## 2300060 远程服务器SSL证书或SSH秘钥不正确
**错误信息**
SSL peer certificate or SSH remote key was not OK.
**错误描述**
远程服务器SSL证书或SSH秘钥不正确。
**可能原因**
无法校验服务器身份,有可能是证书过期了
**处理步骤**
检查证书有效性。
## 2300061 无法识别或错误的HTTP编码格式
**错误信息**
Unrecognized or bad HTTP Content or Transfer-Encoding.
**错误描述**
无法识别或错误的HTTP编码格式。
**可能原因**
HTTP编码格式不正确。
**处理步骤**
排查服务器实现,目前仅支持gzip编码。
## 2300063 超出最大文件大小
**错误信息**
Maximum file size exceeded.
**错误描述**
超出最大文件大小。
**可能原因**
下载的文件过大。
**处理步骤**
排查服务器实现。
## 2300070 服务器磁盘空间不足
**错误信息**
Remote disk full or allocation exceeded.
**错误描述**
服务器磁盘空间不足。
**可能原因**
服务器磁盘已满
**处理步骤**
检查服务器磁盘空间。
## 2300073 服务器返回文件已存在
**错误信息**
Remote file already exists.
**错误描述**
服务器返回文件已存在。
**可能原因**
上传文件的时候,服务器返回文件已经存在。
**处理步骤**
排查服务器。
## 2300077 SSL CA证书不存在或没有访问权限
**错误信息**
Problem with the SSL CA cert (path? access rights?).
**错误描述**
SSL CA证书不存在或没有访问权限。
**可能原因**
证书不存在或者没有访问权限。
**处理步骤**
检查证书是否存在或者有没有访问权限。
## 2300078 URL请求的文件不存在
**错误信息**
Remote file not found.
**错误描述**
URL请求的文件不存在。
**可能原因**
URL请求的文件不存在
**处理步骤**
检查URL请求的文件是否存在。
## 2300094 身份校验失败
**错误信息**
An authentication function returned an error.
**错误描述**
身份校验失败。
**可能原因**
传入的校验身份的字段与服务器不匹配。
**处理步骤**
排查传入的校验身份的字段是否与服务器匹配。
## 2300999 未知错误
**错误信息**
Unknown Other Error.
**错误描述**
未知错误。
**可能原因**
未知错误。
**处理步骤**
未知错误。
# 策略管理错误码
## 2100001 非法参数值
**错误信息**
Invalid parameter value.
**错误描述**
非法参数值
**可能原因**
输入参数取值范围错误。
**处理步骤**
检查输入参数的取值范围是否正确。
## 2100002 连接服务失败
**错误信息**
Operation failed. Cannot connect to service.
**错误描述**
操作失败,连接系统服务发生异常。
**可能原因**
服务发生异常。
**处理步骤**
检查系统服务运行状态是否正常。
## 2100003 系统内部错误
**错误信息**
System internal error.
**错误描述**
系统内部错误。
**可能原因**
1.内存异常。
2.空指针。
**处理步骤**
1.检查内存空间是否充足,清理内存后重试。
2.系统异常,请稍后重试或重启设备。
# 网络共享错误码
## 2200001 非法参数值
**错误信息**
Invalid parameter value.
**错误描述**
非法参数值。
**可能原因**
输入参数取值范围错误。
**处理步骤**
检查输入参数的取值范围是否正确。
## 2200002 连接服务失败
**错误信息**
Operation failed. Cannot connect to service.
**错误描述**
操作失败,连接系统服务发生异常。
**可能原因**
服务发生异常。
**处理步骤**
检查系统服务运行状态是否正常。
## 2200003 系统内部错误
**错误信息**
System internal error.
**错误描述**
系统内部错误。
**可能原因**
1.内存异常。
2.空指针。
**处理步骤**
1.检查内存空间是否充足,清理内存后重试。
2.系统异常,请稍后重试或重启设备。
## 2202004 共享的Iface不可用
**错误信息**
Try to share an unavailable iface.
**错误描述**
使用了不可用的网卡。
**可能原因**
使用的网卡不存在,或网卡名错误。
**处理步骤**
1.通过指令查看共享的网卡是否被创建。
```bash
> ifconfig -a
```
2.检查网卡名是否拼写错误。
## 2202005 WiFi共享失败
**错误信息**
WiFi sharing failed.
**错误描述**
开启WiFi共享失败。
**可能原因**
没有连接网络,获取默认网络失败。
**处理步骤**
检查网络的连接是否正常。
## 2202006 蓝牙共享失败
**错误信息**
Bluetooth sharing failed.
**错误描述**
开启蓝牙共享失败。
**可能原因**
1.未开启蓝牙。
2.没有连接网络,获取默认网络失败。
**处理步骤**
1.点击蓝牙图标,开启蓝牙模式。
2.检查网络的连接是否正常。
## 2202009 网络共享开启转发错误
**错误信息**
Network share enable forwarding error.
**错误描述**
网络共享开启转发错误。
**可能原因**
设置Iptables的规则失败,命令的拼接出错。
**处理步骤**
开启debug日志,检查Ip tables的命令是否拼接出现问题。
## 2202011 无法获取网络共享配置
**错误信息**
Cannot get network sharing configuration.
**错误描述**
无法获取网络共享的配置。
**可能原因**
打开网络共享配置文件失败,文件路径出错。
**处理步骤**
检查配置文件目录。
# Socket 错误码
## 2301001 操作不允许
**错误信息**
Operation not permitted.
**错误描述**
操作不允许。
**可能原因**
非法操作。
**处理步骤**
检查操作步骤。
## 2301002 文件不存在
**错误信息**
No such file or directory.
**错误描述**
文件不存在。
**可能原因**
文件不存在。
**处理步骤**
检查文件名或文件路径。
## 2301003 进程不存在
**错误信息**
No such process.
**错误描述**
进程不存在。
**可能原因**
进程不存在
**处理步骤**
排查进程信息。
## 2301004 系统调用中断
**错误信息**
Interrupted system call.
**错误描述**
系统调用中断。
**可能原因**
系统调用中断。
**处理步骤**
排查系统调用。
**TCP/UDP 错误码说明:**
> TCP/UDP Socket其余错误码映射形式为:2301000 + Linux系统内核错误码errno,关键信息请参考Linux系统内核错误码。
## 2300002 系统内部错误
**错误信息**
System internal error.
**错误描述**
系统内部错误。
**可能原因**
1.内存异常。
2.空指针。
**处理步骤**
1.检查内存空间是否充足,清理内存后重试。
2.系统异常,请稍后重试或重启设备。
## 2303104 中断系统调用
**错误信息**
Interrupted system call.
**错误描述**
中断系统调用。
**可能原因**
调有connect时,可能会导致阻塞时间过长,所以系统产生中断信号,返回EINTR错误。
**处理步骤**
尝试重新走网络连接流程。
## 2303109 错误文件编号
**错误信息**
Bad file number.
**错误描述**
在本地关闭的套接字上进行操作将返回该错误。
**可能原因**
socket fd可能被关闭了,所以发生参数无效的错误。
**处理步骤**
检查socket是否被意外关闭。
## 2303111 资源暂时不可用,请重试
**错误信息**
Resource temporarily unavailable try again.
**错误描述**
系统资源暂时不可用,尝试再次调用。
**可能原因**
系统资源繁忙。
**处理步骤**
重新调用接口。
## 2303188 非套接字的套接字操作
**错误信息**
Socket operation on non-socket.
**错误描述**
参数socket未指定一个套接字描述符。
**可能原因**
参数不是套接字类型的描述符。
**处理步骤**
检查代码描述符的获取是否正确。
## 2303191 socket协议类型错误
**错误信息**
Protocol wrong type for socket.
**错误描述**
参数设置的协议类型错误。
**可能原因**
标识了协议的Socket函数在不支持的socket上进行操作。
如Internet UDP协议不能被标识为SOCK_STREAM socket类型。
**处理步骤**
检查参数设置是否符合协议类型。
## 2303198 网络地址已被使用
**错误信息**
Address already in use.
**错误描述**
地址已被使用。
**可能原因**
如果应用程序试图将套接字绑定到已用于现有套接字的IP地址/端口,或未正确关闭的套接字,或仍在关闭过程中的套接字,则会发生此错误。
**处理步骤**
尝试其他地址。
## 2303199 不能分配请求的地址
**错误信息**
Cannot assign requested address.
**错误描述**
请求的地址在其上下文中无效。
**可能原因**
当远程地址或端口对远程计算机无效时,可能发生该问题。
**处理步骤**
检查地址或端口是否正确。
## 2303210 连接超时
**错误信息**
Connection timed out.
**错误描述**
长时间不能和远程服务器建立连接。
**可能原因**
这种情况一般发生在服务器主机崩溃。
**处理步骤**
本地处理不了,需要确认远程服务器是否发生问题。
## 2303501 SSL为空
**错误信息**
SSL is null.
**错误描述**
参数错误。
**可能原因**
当内部发生函数执行失败时,会获取错误信息,当获取信息为null时,发生该错误。
**处理步骤**
尝试重新执行一遍流程。
## 2303502 tls读取错误
**错误信息**
Error in tls reading.
**错误描述**
等待套接字可读。
**可能原因**
底层socket阻塞。
**处理步骤**
重新执行接收数据的操作。
## 2303503 tls写入错误
**错误信息**
Error in tls writing.
**错误描述**
等待套接字可写。
**可能原因**
发送端缓冲区已满时,底层套接字发送将给出EWOUDLBLOCK错误,这意味着服务器没有读取从客户端发送的消息。
**处理步骤**
需要检查服务器并修复它。
## 2303504 查找x509时出错
**错误信息**
Error looking up x509.
**错误描述**
认证x509证书发生错误,操作未完成。
**可能原因**
本地证书和服务器证书不匹配。
**处理步骤**
检查本地CA跟证书和服务器证书是否匹配。
## 2303505 tls系统调用错误
**错误信息**
Error occurred in the tls system call.
**错误描述**
发生了一些不可恢复的致命I/O错误。
**可能原因**
网络问题,导致通信失败。
**处理步骤**
请参阅Linux系统内核错误码errno以了解详细信息。
## 2303506 清除tls连接出错
**错误信息**
Error clearing tls connection.
**错误描述**
TLS/SSL连接已关闭。
**可能原因**
协议中出现关闭警报时,即连接已完全关闭时,才会返回此结果代码。
**处理步骤**
尝试重新发起连接。
\ No newline at end of file
...@@ -72,7 +72,7 @@ foundation/communication/ ...@@ -72,7 +72,7 @@ foundation/communication/
1. 从@ohos.net.sharing中导入sharing命名空间。 1. 从@ohos.net.sharing中导入sharing命名空间。
2. 设定共享类型 2. 设定共享类型
3. 开始共享 3. 开始共享
4. 止共享 4. 止共享
``` ```
// 引入包名 // 引入包名
import sharing from '@ohos.net.sharing'; import sharing from '@ohos.net.sharing';
...@@ -92,26 +92,28 @@ sharing.stopSharing(this.sharingType,(err)=>{ ...@@ -92,26 +92,28 @@ sharing.stopSharing(this.sharingType,(err)=>{
1. 从@ohos.net.http.d.ts中导入http命名空间。 1. 从@ohos.net.http.d.ts中导入http命名空间。
2. 调用createHttp()方法,创建一个HttpRequest对象。 2. 调用createHttp()方法,创建一个HttpRequest对象。
3. 调用该对象的on()方法,订阅http响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息。 3. 调用该对象的on()方法,订阅http响应头事件,此接口会比request请求先返回。可以根据业务需要订阅此消息。
4. 调用该对象的request()方法,传入http请求的url地址和可选参数,发起网络请求。 4. 调用该对象的request()方法,传入http请求的url地址和可选参数,发起网络请求。
5. 按照实际业务需要,解析返回结果。 5. 按照实际业务需要,解析返回结果。
6. 当该请求使用完毕时,调用destroy()方法主动销毁。 6. 调用该对象的off()方法,取消订阅http响应头事件。
7. 当该请求使用完毕时,调用destroy()方法主动销毁。
``` ```
// 引入包名 // 引入包名
import http from '@ohos.net.http'; import http from '@ohos.net.http';
// 每一个httpRequest对应一个http请求任务,不可复用 // 每一个httpRequest对应一个HTTP请求任务,不可复用
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// 用于订阅http响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息 // 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
httpRequest.on('headersReceive', (data) => { // 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
console.info('header: ' + data.header); httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// 填写http请求的url地址,可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定 // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
method: 'POST', // 可选,默认为“GET” method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
// 开发者根据自身业务需要添加header字段 // 开发者根据自身业务需要添加header字段
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
...@@ -120,21 +122,28 @@ httpRequest.request( ...@@ -120,21 +122,28 @@ httpRequest.request(
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
connectTimeout: 60000, // 可选,默认为60000,即60s expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
readTimeout: 60000, // 可选,默认为60000,即60s usingCache: true, // 可选,默认为true
},(err, data) => { priority: 1, // 可选,默认为1
connectTimeout: 60000, // 可选,默认为60000ms
readTimeout: 60000, // 可选,默认为60000ms
usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性
}, (err, data) => {
if (!err) { if (!err) {
// data.result为http响应内容,可根据业务需要进行解析 // data.result为HTTP响应内容,可根据业务需要进行解析
console.info('Result:' + data.result); console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + data.responseCode); console.info('code:' + JSON.stringify(data.responseCode));
// data.header为http响应头,可根据业务需要进行解析 // data.header为HTTP响应头,可根据业务需要进行解析
console.info('header:' + data.header); console.info('header:' + JSON.stringify(data.header));
console.info('header:' + data.cookies); console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else { } else {
console.info('error:' + err); console.info('error:' + JSON.stringify(err));
// 取消订阅HTTP响应头事件
httpRequest.off('headersReceive');
// 当该请求使用完毕时,调用destroy方法主动销毁。
httpRequest.destroy();
} }
// 当该请求使用完毕时,调用destroy()方法主动销毁。
httpRequest.destroy();
} }
); );
``` ```
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册