提交 9af16a9f 编写于 作者: Y Yangys

Update net docs

Signed-off-by: NYangys <yangyousheng@huawei.com>
上级 292e1b57
...@@ -83,6 +83,7 @@ httpRequest.request( ...@@ -83,6 +83,7 @@ httpRequest.request(
``` ```
## 相关实例 ## 相关实例
针对HTTP数据请求,有以下相关实例可供参考: 针对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
# 网络共享 # 网络共享
## 简介 ## 简介
网络共享管理分享设备已有网络给其他连接设备,支持Wi-Fi热点共享、蓝牙共享和USB共享,同时提供网络共享状态、共享流量查询功能。 网络共享管理分享设备已有网络给其他连接设备,支持Wi-Fi热点共享、蓝牙共享和USB共享,同时提供网络共享状态、共享流量查询功能。
> **说明:** > **说明:**
> 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-sharing.md)。 > 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-sharing.md)。
## 基本概念 ## 基本概念
- WIFI共享:通过WIFI热点共享网络。 - WIFI共享:通过WIFI热点共享网络。
- 蓝牙共享:通过蓝牙共享网络。 - 蓝牙共享:通过蓝牙共享网络。
- USB共享:通过USB共享网络。 - USB共享:通过USB共享网络。
## 约束 ## 约束
- 开发语言:C++ JS - 开发语言:C++ JS
- 系统:linux内核 - 系统:linux内核
- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 场景介绍 ## 场景介绍
网络共享的典型场景有: 网络共享的典型场景有:
- 开启网络共享 - 开启网络共享
- 停止网络共享 - 停止网络共享
- 获取共享网络的数据流量 - 获取共享网络的数据流量
以下分别介绍具体开发方式。 以下分别介绍具体开发方式。
## 接口说明 ## 接口说明
完整的JS API说明以及实例代码请参考:[网络共享](../reference/apis/js-apis-net-sharing.md) 完整的JS API说明以及实例代码请参考:[网络共享](../reference/apis/js-apis-net-sharing.md)
| 类型 | 接口 | 功能说明 | | 类型 | 接口 | 功能说明 |
...@@ -54,18 +61,18 @@ ...@@ -54,18 +61,18 @@
```js ```js
// 从@ohos.net.sharing中导入sharing命名空间 // 从@ohos.net.sharing中导入sharing命名空间
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// 注册监听共享状态的改变 // 注册监听共享状态的改变
sharing.on('sharingStateChange', (error, data) => { sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// 调用startSharing方法,来开启指定类型共享 // 调用startSharing方法,来开启指定类型共享
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
## 停止网络共享 ## 停止网络共享
...@@ -79,18 +86,18 @@ ...@@ -79,18 +86,18 @@
```js ```js
// 从@ohos.net.sharing中导入sharing命名空间 // 从@ohos.net.sharing中导入sharing命名空间
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// 注册监听共享状态的改变 // 注册监听共享状态的改变
sharing.on('sharingStateChange', (error, data) => { sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// 调用stopSharing方法,来停止指定类型共享 // 调用stopSharing方法,来停止指定类型共享
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
## 获取共享网络的数据流量 ## 获取共享网络的数据流量
...@@ -104,27 +111,27 @@ ...@@ -104,27 +111,27 @@
```js ```js
// 从@ohos.net.sharing中导入sharing命名空间 // 从@ohos.net.sharing中导入sharing命名空间
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// 调用startSharing方法,来开启指定类型共享 // 调用startSharing方法,来开启指定类型共享
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
// 调用getStatsTotalBytes方法,来获取共享网络数据量 // 调用getStatsTotalBytes方法,来获取共享网络数据量
sharing.getStatsTotalBytes((error, data) => { sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// 调用stopSharing方法,来停止指定类型共享,共享网络数据量清零 // 调用stopSharing方法,来停止指定类型共享,共享网络数据量清零
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
// 再次调用getStatsTotalBytes方法,共享网络数据量已清零 // 再次调用getStatsTotalBytes方法,共享网络数据量已清零
sharing.getStatsTotalBytes((error, data) => { sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -184,13 +184,11 @@ UDP与TCP流程大体类似,下面以TCP为例: ...@@ -184,13 +184,11 @@ UDP与TCP流程大体类似,下面以TCP为例:
7. TLSSocket连接使用完毕后,主动关闭。 7. TLSSocket连接使用完毕后,主动关闭。
```js ```js
import socket from '@ohos.net.socket' // 创建一个(双向认证)TLS Socket连接,返回一个TLS Socket对象。
let tlsTwoWay = socket.constructTLSSocketInstance();
// 创建一个(双向认证)TLS Socket连接,返回一个TLS Socket对象。
let tlsTwoWay = socket.constructTLSSocketInstance();
// 订阅TLS Socket相关的订阅事件 // 订阅TLS Socket相关的订阅事件
tlsTwoWay.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
...@@ -199,25 +197,25 @@ UDP与TCP流程大体类似,下面以TCP为例: ...@@ -199,25 +197,25 @@ UDP与TCP流程大体类似,下面以TCP为例:
str += String.fromCharCode(dataView.getUint8(i)) str += String.fromCharCode(dataView.getUint8(i))
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tlsTwoWay.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tlsTwoWay.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
// 绑定本地IP地址和端口。 // 绑定本地IP地址和端口。
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
} }
console.log('bind success'); console.log('bind success');
}); });
// 设置通信过程中使用参数 // 设置通信过程中使用参数
let options = { let options = {
ALPNProtocols: ["spdy/1", "http/1.1"], ALPNProtocols: ["spdy/1", "http/1.1"],
// 连接到指定的IP地址和端口。 // 连接到指定的IP地址和端口。
...@@ -238,16 +236,16 @@ UDP与TCP流程大体类似,下面以TCP为例: ...@@ -238,16 +236,16 @@ UDP与TCP流程大体类似,下面以TCP为例:
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // 签名算法 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // 签名算法
cipherSuite: "AES256-SHA256", // 密码套件 cipherSuite: "AES256-SHA256", // 密码套件
}, },
}; };
// 建立连接 // 建立连接
tlsTwoWay.connect(options, (err, data) => { tlsTwoWay.connect(options, (err, data) => {
console.error(err); console.error(err);
console.log(data); console.log(data);
}); });
// 连接使用完毕后,主动关闭。取消相关事件的订阅。 // 连接使用完毕后,主动关闭。取消相关事件的订阅。
tlsTwoWay.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
...@@ -256,59 +254,59 @@ UDP与TCP流程大体类似,下面以TCP为例: ...@@ -256,59 +254,59 @@ UDP与TCP流程大体类似,下面以TCP为例:
tlsTwoWay.off('message'); tlsTwoWay.off('message');
tlsTwoWay.off('connect'); tlsTwoWay.off('connect');
tlsTwoWay.off('close'); tlsTwoWay.off('close');
}); });
// 创建一个(单向认证)TLS Socket连接,返回一个TLS Socket对象。 // 创建一个(单向认证)TLS Socket连接,返回一个TLS Socket对象。
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// 订阅TLS Socket相关的订阅事件 // 订阅TLS Socket相关的订阅事件
tlsTwoWay.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
let str = "" let str = ""
for (let i = 0;i < dataView.byteLength; ++i) { for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i)) str += String.fromCharCode(dataView.getUint8(i))
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tlsTwoWay.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tlsTwoWay.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
// 绑定本地IP地址和端口。 // 绑定本地IP地址和端口。
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
} }
console.log('bind success'); console.log('bind success');
}); });
// 设置通信过程中使用参数 // 设置通信过程中使用参数
let oneWayOptions = { let oneWayOptions = {
address: { address: {
address: "192.168.xxx.xxx", address: "192.168.xxx.xxx",
port: xxxx, port: xxxx,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
ca: ["xxxx","xxxx"], // CA证书 ca: ["xxxx", "xxxx"], // CA证书
cipherSuite: "AES256-SHA256", // 密码套件 cipherSuite: "AES256-SHA256", // 密码套件
}, },
}; };
// 建立连接 // 建立连接
tlsOneWay.connect(oneWayOptions, (err, data) => { tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err); console.error(err);
console.log(data); console.log(data);
}); });
// 连接使用完毕后,主动关闭。取消相关事件的订阅。 // 连接使用完毕后,主动关闭。取消相关事件的订阅。
tlsTwoWay.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
...@@ -317,12 +315,13 @@ UDP与TCP流程大体类似,下面以TCP为例: ...@@ -317,12 +315,13 @@ UDP与TCP流程大体类似,下面以TCP为例:
tlsTwoWay.off('message'); tlsTwoWay.off('message');
tlsTwoWay.off('connect'); tlsTwoWay.off('connect');
tlsTwoWay.off('close'); tlsTwoWay.off('close');
}); });
``` ```
## 相关实例 ## 相关实例
针对Socket连接开发,有以下相关实例可供参考: 针对Socket连接开发,有以下相关实例可供参考:
- [`Socket`:Socket 连接(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Release/Network/Socket) - [`Socket`:Socket 连接(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Release/Network/Socket)
- [使用UDP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH) - [使用UDP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH)
- [使用TCP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) - [使用TCP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo)
# WebSocket连接 # WebSocket连接
## 场景介绍 ## 场景介绍
使用WebSocket建立服务器与客户端的双向连接,需要先通过createWebSocket()方法创建WebSocket对象,然后通过connect()方法连接到服务器。当连接成功后,客户端会收到open事件的回调,之后客户端就可以通过send()方法与服务器进行通信。当服务器发信息给客户端时,客户端会收到message事件的回调。当客户端不要此连接时,可以通过调用close()方法主动断开连接,之后客户端会收到close事件的回调。 使用WebSocket建立服务器与客户端的双向连接,需要先通过createWebSocket()方法创建WebSocket对象,然后通过connect()
方法连接到服务器。当连接成功后,客户端会收到open事件的回调,之后客户端就可以通过send()方法与服务器进行通信。当服务器发信息给客户端时,客户端会收到message事件的回调。当客户端不要此连接时,可以通过调用close()
方法主动断开连接,之后客户端会收到close事件的回调。
若在上述任一过程中发生错误,客户端会收到error事件的回调。 若在上述任一过程中发生错误,客户端会收到error事件的回调。
## 接口说明 ## 接口说明
WebSocket连接功能主要由webSocket模块提供。使用该功能需要申请ohos.permission.INTERNET权限。具体接口说明如下表。 WebSocket连接功能主要由webSocket模块提供。使用该功能需要申请ohos.permission.INTERNET权限。具体接口说明如下表。
...@@ -27,7 +27,6 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申 ...@@ -27,7 +27,6 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申
| on(type: 'error') | 订阅WebSocket的Error事件。 | | on(type: 'error') | 订阅WebSocket的Error事件。 |
| off(type: 'error') | 取消订阅WebSocket的Error事件。 | | off(type: 'error') | 取消订阅WebSocket的Error事件。 |
## 开发步骤 ## 开发步骤
1. 导入需要的webSocket模块。 1. 导入需要的webSocket模块。
...@@ -40,12 +39,12 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申 ...@@ -40,12 +39,12 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申
5. 使用完WebSocket连接之后,主动断开连接。 5. 使用完WebSocket连接之后,主动断开连接。
```js ```js
import webSocket from '@ohos.net.webSocket'; import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://"; var defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => { ws.on('open', (err, value) => {
console.log("on open, status:" + JSON.stringify(value)); console.log("on open, status:" + JSON.stringify(value));
// 当收到on('open')事件时,可以通过send()方法与服务器进行通信 // 当收到on('open')事件时,可以通过send()方法与服务器进行通信
ws.send("Hello, server!", (err, value) => { ws.send("Hello, server!", (err, value) => {
...@@ -55,8 +54,8 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申 ...@@ -55,8 +54,8 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申
console.log("Failed to send the message. Err:" + JSON.stringify(err)); console.log("Failed to send the message. Err:" + JSON.stringify(err));
} }
}); });
}); });
ws.on('message', (err, value) => { ws.on('message', (err, value) => {
console.log("on message, message:" + value); console.log("on message, message:" + value);
// 当收到服务器的`bye`消息时(此消息字段仅为示意,具体字段需要与服务器协商),主动断开连接 // 当收到服务器的`bye`消息时(此消息字段仅为示意,具体字段需要与服务器协商),主动断开连接
if (value === 'bye') { if (value === 'bye') {
...@@ -68,23 +67,24 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申 ...@@ -68,23 +67,24 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申
} }
}); });
} }
}); });
ws.on('close', (err, value) => { ws.on('close', (err, value) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason); console.log("on close, code is " + value.code + ", reason is " + value.reason);
}); });
ws.on('error', (err) => { ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err)); console.log("on error, error:" + JSON.stringify(err));
}); });
ws.connect(defaultIpAddress, (err, value) => { ws.connect(defaultIpAddress, (err, value) => {
if (!err) { if (!err) {
console.log("Connected successfully"); console.log("Connected successfully");
} else { } else {
console.log("Connection failed. Err:" + JSON.stringify(err)); console.log("Connection failed. Err:" + JSON.stringify(err));
} }
}); });
``` ```
## 相关实例 ## 相关实例
针对WebSocket连接的开发,有以下相关实例可供参考: 针对WebSocket连接的开发,有以下相关实例可供参考:
- [`WebSocket`:WebSocket(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Release/Network/WebSocket) - [`WebSocket`:WebSocket(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Release/Network/WebSocket)
\ No newline at end of file
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
本模块提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。 本模块提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。
>**说明:** > **说明:**
> >
>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 >本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> >
...@@ -68,7 +68,8 @@ httpRequest.request( ...@@ -68,7 +68,8 @@ httpRequest.request(
createHttp(): HttpRequest createHttp(): HttpRequest
创建一个HTTP请求,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header事件。每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。 创建一个HTTP请求,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response
Header事件。每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -82,6 +83,7 @@ createHttp(): HttpRequest ...@@ -82,6 +83,7 @@ createHttp(): HttpRequest
```js ```js
import http from '@ohos.net.http'; import http from '@ohos.net.http';
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
``` ```
...@@ -95,8 +97,8 @@ request(url: string, callback: AsyncCallback\<HttpResponse\>):void ...@@ -95,8 +97,8 @@ request(url: string, callback: AsyncCallback\<HttpResponse\>):void
根据URL地址,发起HTTP网络请求,使用callback方式作为异步方法。 根据URL地址,发起HTTP网络请求,使用callback方式作为异步方法。
>**说明:** > **说明:**
>此接口仅支持数据大小为5M以内的数据传输。 > 此接口仅支持数据大小为5M以内的数据传输。
**需要权限**:ohos.permission.INTERNET **需要权限**:ohos.permission.INTERNET
...@@ -121,7 +123,7 @@ request(url: string, callback: AsyncCallback\<HttpResponse\>):void ...@@ -121,7 +123,7 @@ request(url: string, callback: AsyncCallback\<HttpResponse\>):void
| 2300052 | Server returned nothing (no headers, no data). | | 2300052 | Server returned nothing (no headers, no data). |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**错误码说明:** > **错误码说明:**
> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。 > 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。
> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) > HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
...@@ -146,8 +148,8 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR ...@@ -146,8 +148,8 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR
根据URL地址和相关配置项,发起HTTP网络请求,使用callback方式作为异步方法。 根据URL地址和相关配置项,发起HTTP网络请求,使用callback方式作为异步方法。
>**说明:** > **说明:**
>此接口仅支持数据大小为5M以内的数据传输。 > 此接口仅支持数据大小为5M以内的数据传输。
**需要权限**:ohos.permission.INTERNET **需要权限**:ohos.permission.INTERNET
...@@ -197,7 +199,7 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR ...@@ -197,7 +199,7 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR
| 2300094 | An authentication function returned an error. | | 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**错误码说明:** > **错误码说明:**
> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。 > 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。
> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) > HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
...@@ -205,14 +207,14 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR ...@@ -205,14 +207,14 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR
```js ```js
httpRequest.request("EXAMPLE_URL", httpRequest.request("EXAMPLE_URL",
{ {
method: http.RequestMethod.GET, method: http.RequestMethod.GET,
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
readTimeout: 60000, readTimeout: 60000,
connectTimeout: 60000 connectTimeout: 60000
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
console.info('Result:' + data.result); console.info('Result:' + data.result);
console.info('code:' + data.responseCode); console.info('code:' + data.responseCode);
...@@ -223,7 +225,7 @@ httpRequest.request("EXAMPLE_URL", ...@@ -223,7 +225,7 @@ httpRequest.request("EXAMPLE_URL",
} else { } else {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
} }
}); });
``` ```
### request ### request
...@@ -232,8 +234,8 @@ request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\> ...@@ -232,8 +234,8 @@ request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。 根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。
>**说明:** > **说明:**
>此接口仅支持数据大小为5M以内的数据传输。 > 此接口仅支持数据大小为5M以内的数据传输。
**需要权限**:ohos.permission.INTERNET **需要权限**:ohos.permission.INTERNET
...@@ -288,7 +290,7 @@ request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\> ...@@ -288,7 +290,7 @@ request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
| 2300094 | An authentication function returned an error. | | 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**错误码说明:** > **错误码说明:**
> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。 > 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。
> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) > HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
...@@ -337,8 +339,8 @@ on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void ...@@ -337,8 +339,8 @@ on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void
订阅HTTP Response Header 事件。 订阅HTTP Response Header 事件。
>**说明:** > **说明:**
>此接口已废弃,建议使用[on('headersReceive')<sup>8+</sup>](#onheadersreceive8)替代。 > 此接口已废弃,建议使用[on('headersReceive')<sup>8+</sup>](#onheadersreceive8)替代。
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -363,7 +365,7 @@ off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void ...@@ -363,7 +365,7 @@ off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void
取消订阅HTTP Response Header 事件。 取消订阅HTTP Response Header 事件。
>**说明:** > **说明:**
> >
>1. 此接口已废弃,建议使用[off('headersReceive')<sup>8+</sup>](#offheadersreceive8)替代。 >1. 此接口已废弃,建议使用[off('headersReceive')<sup>8+</sup>](#offheadersreceive8)替代。
> >
...@@ -413,8 +415,8 @@ off(type: 'headersReceive', callback?: Callback\<Object\>): void ...@@ -413,8 +415,8 @@ off(type: 'headersReceive', callback?: Callback\<Object\>): void
取消订阅HTTP Response Header 事件。 取消订阅HTTP Response Header 事件。
>**说明:** > **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 > 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -462,11 +464,11 @@ httpRequest.once('headersReceive', (header) => { ...@@ -462,11 +464,11 @@ httpRequest.once('headersReceive', (header) => {
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | 否 | 请求方式。 | | method | [RequestMethod](#requestmethod) | 否 | 请求方式,默认为GET。 |
| 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,以UTF-8编码形式作为请求体。<sup>6+</sup><br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求参数的补充。开发者需传入Encode编码后的string类型参数,Object类型的参数无需预编码,参数内容会拼接到URL中进行发送;ArrayBuffer类型的参数不会做拼接处理。<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 | 否 | 优先级,范围\[0,1000],默认是0。 |
| 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。 |
...@@ -544,7 +546,7 @@ request方法回调函数的返回值类型。 ...@@ -544,7 +546,7 @@ 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字段返回。 | | 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> | string | 是 | 服务器返回的 cookies。 | | cookies<sup>8+</sup> | string | 是 | 服务器返回的 cookies。 |
## http.createHttpResponseCache<sup>9+</sup> ## http.createHttpResponseCache<sup>9+</sup>
...@@ -571,6 +573,7 @@ createHttpResponseCache(cacheSize?: number): HttpResponseCache ...@@ -571,6 +573,7 @@ createHttpResponseCache(cacheSize?: number): HttpResponseCache
```js ```js
import http from '@ohos.net.http'; import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache(); let httpResponseCache = http.createHttpResponseCache();
``` ```
...@@ -653,6 +656,7 @@ httpResponseCache.delete(err => { ...@@ -653,6 +656,7 @@ httpResponseCache.delete(err => {
console.info('delete success'); console.info('delete success');
}); });
``` ```
### delete<sup>9+</sup> ### delete<sup>9+</sup>
delete(): Promise\<void\> delete(): Promise\<void\>
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
```js ```js
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
``` ```
## connection.createNetConnection ## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
...@@ -34,10 +35,10 @@ createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnectio ...@@ -34,10 +35,10 @@ createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnectio
**示例:** **示例:**
```js ```js
// 关注默认网络 // 关注默认网络, 不需要传参
let netConnection = connection.createNetConnection() let netConnection = connection.createNetConnection()
// 关注蜂窝网络 // 关注蜂窝网络,需要传入相关网络特征,timeout参数未传入说明未使用超时时间,此时timeout为0
let netConnectionCellular = connection.createNetConnection({ let netConnectionCellular = connection.createNetConnection({
netCapabilities: { netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR] bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
...@@ -164,7 +165,7 @@ getAppNet(callback: AsyncCallback\<NetHandle>): void ...@@ -164,7 +165,7 @@ getAppNet(callback: AsyncCallback\<NetHandle>): void
**示例:** **示例:**
```js ```js
connection.getAppNet(function(error, data) { connection.getAppNet(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -774,8 +775,7 @@ connection.disableAirplaneMode().then(function (error) { ...@@ -774,8 +775,7 @@ connection.disableAirplaneMode().then(function (error) {
reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
向网络管理报告网络处于可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 向网络管理报告网络处于可用状态,使用callback方式作为异步方法。
使用callback方式作为异步方法。
**需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET **需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET
...@@ -812,8 +812,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -812,8 +812,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
向网络管理报告网络处于可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 向网络管理报告网络处于可用状态,使用Promise方式作为异步方法。
使用Promise方式作为异步方法。
**需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET **需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET
...@@ -826,9 +825,7 @@ reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt; ...@@ -826,9 +825,7 @@ reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 | | netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 | | -------- | -------- | | Promise&lt;void&gt; | 无返回值的Promise对象。 |
| -------- | -------- |
| Promise&lt;void&gt; | 无返回值的Promise对象。 |
**错误码:** **错误码:**
...@@ -854,8 +851,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -854,8 +851,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 使用callback方式作为异步方法。
使用callback方式作为异步方法。
**需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET **需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET
...@@ -892,8 +888,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -892,8 +888,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 使用Promise方式作为异步方法。
使用Promise方式作为异步方法。
**需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET **需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET
...@@ -906,9 +901,7 @@ reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt; ...@@ -906,9 +901,7 @@ reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 | | netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 | | -------- | -------- | | Promise&lt;void&gt; | 无返回值的Promise对象。 |
| -------- | -------- |
| Promise&lt;void&gt; | 无返回值的Promise对象。 |
**错误码:** **错误码:**
...@@ -1038,7 +1031,6 @@ register(callback: AsyncCallback\<void>): void ...@@ -1038,7 +1031,6 @@ register(callback: AsyncCallback\<void>): void
| 2101008 | The callback is not exists. | | 2101008 | The callback is not exists. |
| 2101022 | The number of requests exceeded the maximum. | | 2101022 | The number of requests exceeded the maximum. |
**示例:** **示例:**
```js ```js
...@@ -1196,7 +1188,8 @@ netCon.unregister(function (error) { ...@@ -1196,7 +1188,8 @@ netCon.unregister(function (error) {
### on('netConnectionPropertiesChange') ### on('netConnectionPropertiesChange')
on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties:
ConnectionProperties }>): void
订阅网络连接信息变化事件。 订阅网络连接信息变化事件。
...@@ -1353,6 +1346,7 @@ bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): ...@@ -1353,6 +1346,7 @@ bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>):
```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();
...@@ -1363,6 +1357,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1363,6 +1357,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
netHandle.bindSocket(tcp, (error, data) => { netHandle.bindSocket(tcp, (error, data) => {
if (error) { if (error) {
...@@ -1382,6 +1377,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1382,6 +1377,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
...@@ -1431,6 +1427,7 @@ bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>; ...@@ -1431,6 +1427,7 @@ bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>;
```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();
...@@ -1441,6 +1438,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1441,6 +1438,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
netHandle.bindSocket(tcp).then((data) => { netHandle.bindSocket(tcp).then((data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
...@@ -1458,6 +1456,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1458,6 +1456,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
...@@ -1732,8 +1731,5 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -1732,8 +1731,5 @@ connection.getDefaultNet().then(function (netHandle) {
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | -- |------------------------------ | | address | string | 是 |地址。 | | family |
| ------- | ------ | -- |------------------------------ | number | 否 |IPv4 = 1,IPv6 = 2,默认IPv4。 | | port | number | 否 |端口,取值范围\[0, 65535]。 |
| address | string | 是 |地址。 |
| family | number | 否 |IPv4 = 1,IPv6 = 2,默认IPv4。 |
| port | number | 否 |端口,取值范围\[0, 65535]。 |
...@@ -386,6 +386,74 @@ ethernet.getAllActiveIfaces().then((data) => { ...@@ -386,6 +386,74 @@ ethernet.getAllActiveIfaces().then((data) => {
}); });
``` ```
## ethernet.on('interfaceStateChange')<sup>10+</sup>
on(type: 'interfaceStateChange', callback: Callback\<{ iface: string, active: boolean }\>): void
注册网卡热插拔事件,使用callback方式作为异步方法。
**系统接口**:此接口为系统接口。
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Communication.NetManager.Ethernet
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| type | string | 是 | 订阅的事件类型,'interfaceStateChange'。 |
| callback | AsyncCallback\<{ iface: string, active: boolean }\> | 是 | 回调函数。<br>iface:网卡名称。<br>active:是否处于激活状态(true:激活;false:未激活) |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Applicable only to system applications. |
| 401 | Parameter error. |
**示例:**
```js
ethernet.on('interfaceStateChange', (data) => {
console.log('on interfaceSharingStateChange:' + JSON.stringify(data));
});
```
## ethernet.off('interfaceStateChange')<sup>10+</sup>
off(type: 'interfaceStateChange', callback?: Callback\<{ iface: string, active: boolean }\>): void
注销网卡热插拔事件,使用callback方式作为异步方法。
**系统接口**:此接口为系统接口。
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Communication.NetManager.Ethernet
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| type | string | 是 | 订阅的事件类型,'interfaceStateChange'。 |
| callback | AsyncCallback\<{ iface: string, active: boolean }> | 否 | 回调函数。<br>iface:网卡名称。<br>active:是否处于激活状态(true:激活;false:未激活) |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Applicable only to system applications. |
| 401 | Parameter error. |
**示例:**
```js
ethernet.off('interfaceStateChange');
```
## InterfaceConfiguration ## InterfaceConfiguration
以太网连接配置网络信息。 以太网连接配置网络信息。
......
...@@ -46,7 +46,9 @@ policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, da ...@@ -46,7 +46,9 @@ policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, da
this.callBack(error, data); this.callBack(error, data);
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); }
)
;
``` ```
## policy.setBackgroundPolicy ## policy.setBackgroundPolicy
...@@ -84,7 +86,7 @@ setBackgroundPolicy(isAllowed: boolean): Promise\<void> ...@@ -84,7 +86,7 @@ setBackgroundPolicy(isAllowed: boolean): Promise\<void>
**示例:** **示例:**
```js ```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -151,7 +153,7 @@ isBackgroundAllowed(): Promise\<boolean>; ...@@ -151,7 +153,7 @@ isBackgroundAllowed(): Promise\<boolean>;
**示例:** **示例:**
```js ```js
policy.isBackgroundAllowed().then(function(error, data) { policy.isBackgroundAllowed().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -236,7 +238,7 @@ setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\<void>; ...@@ -236,7 +238,7 @@ setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\<void>;
let param = { let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
} }
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function(error, data) { policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -313,7 +315,7 @@ getPolicyByUid(uid: number): Promise\<NetUidPolicy>; ...@@ -313,7 +315,7 @@ getPolicyByUid(uid: number): Promise\<NetUidPolicy>;
**示例:** **示例:**
```js ```js
policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -390,7 +392,7 @@ function getUidsByPolicy(policy: NetUidPolicy): Promise\<Array\<number>>; ...@@ -390,7 +392,7 @@ function getUidsByPolicy(policy: NetUidPolicy): Promise\<Array\<number>>;
**示例:** **示例:**
```js ```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -456,7 +458,7 @@ getNetQuotaPolicies(): Promise\<Array\<NetQuotaPolicy>>; ...@@ -456,7 +458,7 @@ getNetQuotaPolicies(): Promise\<Array\<NetQuotaPolicy>>;
**示例:** **示例:**
```js ```js
policy.getNetQuotaPolicies().then(function(error, data) { policy.getNetQuotaPolicies().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -493,8 +495,18 @@ setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>, callback: AsyncCallba ...@@ -493,8 +495,18 @@ setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>, callback: AsyncCallba
**示例:** **示例:**
```js ```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), let param = {
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; 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); this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => { policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => {
...@@ -537,11 +549,21 @@ setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>): Promise\<void>; ...@@ -537,11 +549,21 @@ setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>): Promise\<void>;
**示例:** **示例:**
```js ```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), let param = {
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; 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); this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) { policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -619,7 +641,7 @@ restoreAllPolicies(iccid: string): Promise\<void>; ...@@ -619,7 +641,7 @@ restoreAllPolicies(iccid: string): Promise\<void>;
```js ```js
this.firstParam = iccid; this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam).then(function(error, data){ policy.restoreAllPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -706,7 +728,7 @@ isUidNetAllowed(uid: number, isMetered: boolean): Promise\<boolean>; ...@@ -706,7 +728,7 @@ isUidNetAllowed(uid: number, isMetered: boolean): Promise\<boolean>;
let param = { let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -792,7 +814,7 @@ isUidNetAllowed(uid: number, iface: string): Promise\<boolean>; ...@@ -792,7 +814,7 @@ isUidNetAllowed(uid: number, iface: string): Promise\<boolean>;
let param = { let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam uid: Number.parseInt(this.firstParam), iface: this.secondParam
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function(error, data) { policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -877,7 +899,7 @@ setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\<void>; ...@@ -877,7 +899,7 @@ setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\<void>;
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -943,7 +965,7 @@ getDeviceIdleAllowList(): Promise\<Array\<number>>; ...@@ -943,7 +965,7 @@ getDeviceIdleAllowList(): Promise\<Array\<number>>;
**示例:** **示例:**
```js ```js
policy.getDeviceIdleAllowList().then(function(error, data) { policy.getDeviceIdleAllowList().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1021,7 +1043,7 @@ getBackgroundPolicyByUid(uid: number): Promise\<NetBackgroundPolicy>; ...@@ -1021,7 +1043,7 @@ getBackgroundPolicyByUid(uid: number): Promise\<NetBackgroundPolicy>;
```js ```js
this.firstParam = uid this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1098,11 +1120,11 @@ resetPolicies(iccid: string): Promise\<void>; ...@@ -1098,11 +1120,11 @@ resetPolicies(iccid: string): Promise\<void>;
**示例:** **示例:**
```js ```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
}) })
this.firstParam = iccid this.firstParam = iccid
policy.resetPolicies(this.firstParam).then(function(error, data) { policy.resetPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1189,7 +1211,7 @@ updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): ...@@ -1189,7 +1211,7 @@ updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType):
let param = { let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
} }
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function(error, data) { 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(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1274,7 +1296,7 @@ setPowerSaveAllowList(uid: number, isAllowed: boolean): Promise\<void>; ...@@ -1274,7 +1296,7 @@ setPowerSaveAllowList(uid: number, isAllowed: boolean): Promise\<void>;
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1340,7 +1362,7 @@ getPowerSaveAllowList(): Promise\<Array\<number>>; ...@@ -1340,7 +1362,7 @@ getPowerSaveAllowList(): Promise\<Array\<number>>;
**示例:** **示例:**
```js ```js
policy.getPowerSaveAllowList().then(function(error, data) { policy.getPowerSaveAllowList().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -1540,10 +1562,8 @@ policy.on('netBackgroundPolicyChange', (data) => { ...@@ -1540,10 +1562,8 @@ policy.on('netBackgroundPolicyChange', (data) => {
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
| 参数名 | 值 | 说明 | | 参数名 | 值 | 说明 | | ---------------------- | - | ------- | | REMIND_TYPE_WARNING | 1 | 警告提醒 | | REMIND_TYPE_LIMIT | 2 |
| ---------------------- | - | ------- | 限制提醒 |
| REMIND_TYPE_WARNING | 1 | 警告提醒 |
| REMIND_TYPE_LIMIT | 2 | 限制提醒 |
## NetUidPolicy ## NetUidPolicy
......
...@@ -194,7 +194,8 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void ...@@ -194,7 +194,8 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI, (error) => { sharing.startSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
...@@ -243,7 +244,8 @@ startSharing(type: SharingIfaceType): Promise\<void> ...@@ -243,7 +244,8 @@ startSharing(type: SharingIfaceType): Promise\<void>
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI).then(() => { sharing.startSharing(SHARING_WIFI).then(() => {
console.log("start wifi sharing successful"); console.log("start wifi sharing successful");
}).catch(error => { }).catch(error => {
...@@ -287,7 +289,8 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void ...@@ -287,7 +289,8 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI, (error) => { sharing.stopSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
...@@ -334,7 +337,8 @@ stopSharing(type: SharingIfaceType): Promise\<void> ...@@ -334,7 +337,8 @@ stopSharing(type: SharingIfaceType): Promise\<void>
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI).then(() => { sharing.stopSharing(SHARING_WIFI).then(() => {
console.log("stop wifi sharing successful"); console.log("stop wifi sharing successful");
}).catch(error => { }).catch(error => {
...@@ -588,7 +592,8 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<strin ...@@ -588,7 +592,8 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<strin
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => { 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));
...@@ -633,7 +638,8 @@ getSharingIfaces(state: SharingIfaceState): Promise\<Array\<string>> ...@@ -633,7 +638,8 @@ getSharingIfaces(state: SharingIfaceState): Promise\<Array\<string>>
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => { sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
...@@ -674,7 +680,8 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceSta ...@@ -674,7 +680,8 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceSta
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI, (error, data) => { 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));
...@@ -719,7 +726,8 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState> ...@@ -719,7 +726,8 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState>
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI).then(data => { sharing.getSharingState(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
...@@ -760,7 +768,8 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<strin ...@@ -760,7 +768,8 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<strin
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI, (error, data) => { 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));
...@@ -805,7 +814,8 @@ getSharableRegexes(type: SharingIfaceType): Promise\<Array\<string>> ...@@ -805,7 +814,8 @@ getSharableRegexes(type: SharingIfaceType): Promise\<Array\<string>>
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI).then(data => { sharing.getSharableRegexes(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
...@@ -842,8 +852,8 @@ on(type: 'sharingStateChange', callback: Callback\<boolean>): void ...@@ -842,8 +852,8 @@ on(type: 'sharingStateChange', callback: Callback\<boolean>): void
**示例:** **示例:**
```js ```js
sharing.on('sharingStateChange', (data) => { sharing.on('sharingStateChange', (data) => {
console.log('on sharingStateChange:' + JSON.stringify(data)); console.log('on sharingStateChange: ' + JSON.stringify(data));
}); });
``` ```
...@@ -883,7 +893,8 @@ sharing.off('sharingStateChange', (data) => { ...@@ -883,7 +893,8 @@ sharing.off('sharingStateChange', (data) => {
## sharing.on('interfaceSharingStateChange') ## sharing.on('interfaceSharingStateChange')
on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state:
SharingIfaceState }>): void
注册网卡网络共享状态变化事件,使用callback方式作为异步方法。 注册网卡网络共享状态变化事件,使用callback方式作为异步方法。
...@@ -910,14 +921,15 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface ...@@ -910,14 +921,15 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface
**示例:** **示例:**
```js ```js
sharing.on('interfaceSharingStateChange', (data) => { sharing.on('interfaceSharingStateChange', (data) => {
console.log('on interfaceSharingStateChange:' + JSON.stringify(data)); console.log('on interfaceSharingStateChange:' + JSON.stringify(data));
}); });
``` ```
## sharing.off('interfaceSharingStateChange') ## sharing.off('interfaceSharingStateChange')
off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state:
SharingIfaceState }>): void
注销网卡网络共享状态变化事件,使用callback方式作为异步方法。 注销网卡网络共享状态变化事件,使用callback方式作为异步方法。
...@@ -978,8 +990,8 @@ on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void ...@@ -978,8 +990,8 @@ on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void
**示例:** **示例:**
```js ```js
sharing.on('sharingUpstreamChange', (data) => { sharing.on('sharingUpstreamChange', (data) => {
console.log('on sharingUpstreamChange:' + JSON.stringify(data)); console.log('on sharingUpstreamChange:' + JSON.stringify(data));
}); });
``` ```
......
...@@ -5,11 +5,12 @@ ...@@ -5,11 +5,12 @@
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
使用WebSocket建立服务器与客户端的双向连接,需要先通过[createWebSocket](#websocketcreatewebsocket)方法创建[WebSocket](#websocket)对象,然后通过[connect](#connect)方法连接到服务器。当连接成功后,客户端会收到[open](#onopen)事件的回调,之后客户端就可以通过[send](#send)方法与服务器进行通信。当服务器发信息给客户端时,客户端会收到[message](#onmessage)事件的回调。当客户端不要此连接时,可以通过调用[close](#close)方法主动断开连接,之后客户端会收到[close](#onclose)事件的回调。 使用WebSocket建立服务器与客户端的双向连接,需要先通过[createWebSocket](#websocketcreatewebsocket)方法创建[WebSocket](#websocket)对象,然后通过[connect](#connect)方法连接到服务器。
当连接成功后,客户端会收到[open](#onopen)事件的回调,之后客户端就可以通过[send](#send)方法与服务器进行通信。
当服务器发信息给客户端时,客户端会收到[message](#onmessage)事件的回调。当客户端不要此连接时,可以通过调用[close](#close)方法主动断开连接,之后客户端会收到[close](#onclose)事件的回调。
若在上述任一过程中发生错误,客户端会收到[error](#onerror)事件的回调。 若在上述任一过程中发生错误,客户端会收到[error](#onerror)事件的回调。
## 导入模块 ## 导入模块
```js ```js
...@@ -21,9 +22,13 @@ import webSocket from '@ohos.net.webSocket'; ...@@ -21,9 +22,13 @@ import webSocket from '@ohos.net.webSocket';
```js ```js
import webSocket from '@ohos.net.webSocket'; import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://"; let defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => { ws.on('open', (err, value) => {
if (err != undefined) {
console.log(JSON.stringify(err))
return
}
console.log("on open, status:" + value['status'] + ", message:" + value['message']); console.log("on open, status:" + value['status'] + ", message:" + value['message']);
// 当收到on('open')事件时,可以通过send()方法与服务器进行通信 // 当收到on('open')事件时,可以通过send()方法与服务器进行通信
ws.send("Hello, server!", (err, value) => { ws.send("Hello, server!", (err, value) => {
...@@ -82,7 +87,6 @@ createWebSocket(): WebSocket ...@@ -82,7 +87,6 @@ createWebSocket(): WebSocket
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
``` ```
## WebSocket ## WebSocket
在调用WebSocket的方法前,需要先通过[webSocket.createWebSocket](#websocketcreatewebsocket)创建一个WebSocket。 在调用WebSocket的方法前,需要先通过[webSocket.createWebSocket](#websocketcreatewebsocket)创建一个WebSocket。
...@@ -93,6 +97,9 @@ connect(url: string, callback: AsyncCallback\<boolean\>): void ...@@ -93,6 +97,9 @@ connect(url: string, callback: AsyncCallback\<boolean\>): void
根据URL地址,建立一个WebSocket连接,使用callback方式作为异步方法。 根据URL地址,建立一个WebSocket连接,使用callback方式作为异步方法。
> **说明:**
> 可通过监听error事件获得该接口的执行结果,错误发生时会得到错误码:200。
**需要权限**:ohos.permission.INTERNET **需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -125,13 +132,15 @@ ws.connect(url, (err, value) => { ...@@ -125,13 +132,15 @@ ws.connect(url, (err, value) => {
}); });
``` ```
### connect ### connect
connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void
根据URL地址和header,建立一个WebSocket连接,使用callback方式作为异步方法。 根据URL地址和header,建立一个WebSocket连接,使用callback方式作为异步方法。
> **说明:**
> 可通过监听error事件获得该接口的执行结果,错误发生时会得到错误码:200。
**需要权限**:ohos.permission.INTERNET **需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -170,13 +179,15 @@ ws.connect(url, { ...@@ -170,13 +179,15 @@ ws.connect(url, {
}); });
``` ```
### connect ### connect
connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\> connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\>
根据URL地址和header,建立一个WebSocket连接,使用Promise方式作为异步方法。 根据URL地址和header,建立一个WebSocket连接,使用Promise方式作为异步方法。
> **说明:**
> 可通过监听error事件获得该接口的执行结果,错误发生时会得到错误码:200。
**需要权限**:ohos.permission.INTERNET **需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -214,7 +225,6 @@ promise.then((value) => { ...@@ -214,7 +225,6 @@ promise.then((value) => {
}); });
``` ```
### send ### send
send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
...@@ -255,7 +265,6 @@ ws.connect(url, (err, value) => { ...@@ -255,7 +265,6 @@ ws.connect(url, (err, value) => {
}); });
``` ```
### send ### send
send(data: string | ArrayBuffer): Promise\<boolean\> send(data: string | ArrayBuffer): Promise\<boolean\>
...@@ -300,7 +309,6 @@ ws.connect(url, (err, value) => { ...@@ -300,7 +309,6 @@ ws.connect(url, (err, value) => {
}); });
``` ```
### close ### close
close(callback: AsyncCallback\<boolean\>): void close(callback: AsyncCallback\<boolean\>): void
...@@ -328,7 +336,6 @@ close(callback: AsyncCallback\<boolean\>): void ...@@ -328,7 +336,6 @@ close(callback: AsyncCallback\<boolean\>): void
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close((err, value) => { ws.close((err, value) => {
if (!err) { if (!err) {
console.log("close success") console.log("close success")
...@@ -338,7 +345,6 @@ ws.close((err, value) => { ...@@ -338,7 +345,6 @@ ws.close((err, value) => {
}); });
``` ```
### close ### close
close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
...@@ -367,7 +373,6 @@ close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void ...@@ -367,7 +373,6 @@ close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close({ ws.close({
code: 1000, code: 1000,
reason: "your reason" reason: "your reason"
...@@ -380,7 +385,6 @@ ws.close({ ...@@ -380,7 +385,6 @@ ws.close({
}); });
``` ```
### close ### close
close(options?: WebSocketCloseOptions): Promise\<boolean\> close(options?: WebSocketCloseOptions): Promise\<boolean\>
...@@ -414,7 +418,6 @@ close(options?: WebSocketCloseOptions): Promise\<boolean\> ...@@ -414,7 +418,6 @@ close(options?: WebSocketCloseOptions): Promise\<boolean\>
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.close({ let promise = ws.close({
code: 1000, code: 1000,
reason: "your reason" reason: "your reason"
...@@ -426,7 +429,6 @@ promise.then((value) => { ...@@ -426,7 +429,6 @@ promise.then((value) => {
}); });
``` ```
### on('open') ### on('open')
on(type: 'open', callback: AsyncCallback\<Object\>): void on(type: 'open', callback: AsyncCallback\<Object\>): void
...@@ -442,7 +444,6 @@ on(type: 'open', callback: AsyncCallback\<Object\>): void ...@@ -442,7 +444,6 @@ on(type: 'open', callback: AsyncCallback\<Object\>): void
| type | string | 是 | 'open':WebSocket的打开事件。 | | type | string | 是 | 'open':WebSocket的打开事件。 |
| callback | AsyncCallback\<Object\> | 是 | 回调函数。 | | callback | AsyncCallback\<Object\> | 是 | 回调函数。 |
**示例:** **示例:**
```js ```js
...@@ -452,15 +453,14 @@ ws.on('open', (err, value) => { ...@@ -452,15 +453,14 @@ ws.on('open', (err, value) => {
}); });
``` ```
### off('open') ### off('open')
off(type: 'open', callback?: AsyncCallback\<Object\>): void off(type: 'open', callback?: AsyncCallback\<Object\>): void
取消订阅WebSocket的打开事件,使用callback方式作为异步方法。 取消订阅WebSocket的打开事件,使用callback方式作为异步方法。
>**说明:** > **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 > 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -483,15 +483,14 @@ ws.on('open', callback1); ...@@ -483,15 +483,14 @@ ws.on('open', callback1);
ws.off('open', callback1); ws.off('open', callback1);
``` ```
### on('message') ### on('message')
on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void
订阅WebSocket的接收到服务器消息事件,使用callback方式作为异步方法。每个消息最大长度为4K,超过4K自动分片。 订阅WebSocket的接收到服务器消息事件,使用callback方式作为异步方法。每个消息最大长度为4K,超过4K自动分片。
>**说明:** > **说明:**
>AsyncCallback中的数据可以是字符串(API 6)或ArrayBuffer(API 8)。 > AsyncCallback中的数据可以是字符串(API 6)或ArrayBuffer(API 8)。
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -511,16 +510,15 @@ ws.on('message', (err, value) => { ...@@ -511,16 +510,15 @@ ws.on('message', (err, value) => {
}); });
``` ```
### off('message') ### off('message')
off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void
取消订阅WebSocket的接收到服务器消息事件,使用callback方式作为异步方法。每个消息最大长度为4K,超过4K自动分片。 取消订阅WebSocket的接收到服务器消息事件,使用callback方式作为异步方法。每个消息最大长度为4K,超过4K自动分片。
>**说明:** > **说明:**
>AsyncCallback中的数据可以是字符串(API 6)或ArrayBuffer(API 8)。 > AsyncCallback中的数据可以是字符串(API 6)或ArrayBuffer(API 8)。
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 > 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -538,7 +536,6 @@ let ws = webSocket.createWebSocket(); ...@@ -538,7 +536,6 @@ let ws = webSocket.createWebSocket();
ws.off('message'); ws.off('message');
``` ```
### on('close') ### on('close')
on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void
...@@ -563,15 +560,14 @@ ws.on('close', (err, value) => { ...@@ -563,15 +560,14 @@ ws.on('close', (err, value) => {
}); });
``` ```
### off('close') ### off('close')
off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void
取消订阅WebSocket的关闭事件,使用callback方式作为异步方法。 取消订阅WebSocket的关闭事件,使用callback方式作为异步方法。
>**说明:** > **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 > 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -589,7 +585,6 @@ let ws = webSocket.createWebSocket(); ...@@ -589,7 +585,6 @@ let ws = webSocket.createWebSocket();
ws.off('close'); ws.off('close');
``` ```
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback): void on(type: 'error', callback: ErrorCallback): void
...@@ -603,7 +598,7 @@ on(type: 'error', callback: ErrorCallback): void ...@@ -603,7 +598,7 @@ on(type: 'error', callback: ErrorCallback): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------- | | -------- | ------------- | ---- | ------------------------------- |
| type | string | 是 | 'error':WebSocket的Error事件。 | | type | string | 是 | 'error':WebSocket的Error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 | | callback | ErrorCallback | 是 | 回调函数。<br>常见错误码:200 |
**示例:** **示例:**
...@@ -614,15 +609,14 @@ ws.on('error', (err) => { ...@@ -614,15 +609,14 @@ ws.on('error', (err) => {
}); });
``` ```
### off('error') ### off('error')
off(type: 'error', callback?: ErrorCallback): void off(type: 'error', callback?: ErrorCallback): void
取消订阅WebSocket的Error事件,使用callback方式作为异步方法。 取消订阅WebSocket的Error事件,使用callback方式作为异步方法。
>**说明:** > **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 > 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -640,7 +634,6 @@ let ws = webSocket.createWebSocket(); ...@@ -640,7 +634,6 @@ let ws = webSocket.createWebSocket();
ws.off('error'); ws.off('error');
``` ```
## WebSocketRequestOptions ## WebSocketRequestOptions
建立WebSocket连接时,可选参数的类型和说明。 建立WebSocket连接时,可选参数的类型和说明。
...@@ -651,7 +644,6 @@ ws.off('error'); ...@@ -651,7 +644,6 @@ ws.off('error');
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| header | Object | 否 | 建立WebSocket连接可选参数,代表建立连接时携带的HTTP头信息。参数内容自定义,也可以不指定。 | | header | Object | 否 | 建立WebSocket连接可选参数,代表建立连接时携带的HTTP头信息。参数内容自定义,也可以不指定。 |
## WebSocketCloseOptions ## WebSocketCloseOptions
关闭WebSocket连接时,可选参数的类型和说明。 关闭WebSocket连接时,可选参数的类型和说明。
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册