如果你也对鸿蒙开发感兴趣,加入“Harmony自习室”吧!扫描下方名片,关注公众号,公众号更新更快,同时也有更多学习资料和技术讨论群。

1、概述
鸿蒙的网络管理模块主要提供以下功能:
-
HTTP数据请求:通过HTTP发起一个数据请求。
-
WebSocket连接:使用WebSocket建立服务器与客户端的双向连接。
-
Socket连接:通过Socket进行数据传输。
需要注意的是,使用网络管理模块相关功能时,需要申请相应的权限。
-
ohos.permission.GET_NETWORK_INFO
获取网络连接信息
-
ohos.permission.SET_NETWORK_INFO
修改网络连接状态
-
ohos.permission.INTERNET
运行程序进行网络连接
本文先介绍发起HTTP数据请求与WebSocket连接。
2、发起HTTP数据请求
使用该功能需要申请ohos.permission.INTERNET权限
对于HTTP请求而言,常见的有GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT等请求方法。
主要涉及的接口有:

👉🏻 一般情况下,使用request接口,具体开发步骤如下:

实例demo如下:
// 引入包名import { http } from '@kit.NetworkKit';import { BusinessError } from '@kit.BasicServicesKit';// 每一个httpRequest对应一个HTTP请求任务,不可复用let httpRequest = http.createHttp();// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。8+httpRequest.on('headersReceive', (header) => {console.info('header: ' + JSON.stringify(header));});httpRequest.request(// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定"EXAMPLE_URL",{method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET// 开发者根据自身业务需要添加header字段header: {'Content-Type': 'application/json'},// 当使用POST请求时此字段用于传递请求体内容,具体格式与服务端协商确定extraData: "data to send",expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型usingCache: true, // 可选,默认为truepriority: 1, // 可选,默认为1connectTimeout: 60000, // 可选,默认为60000msreadTimeout: 60000, // 可选,默认为60000msusingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定usingProxy: false, // 可选,默认不使用网络代理,自API 10开始支持该属性caPath:'/path/to/cacert.pem', // 可选,默认使用系统预制证书,自API 10开始支持该属性clientCert: { // 可选,默认不使用客户端证书,自API 11开始支持该属性certPath: '/path/to/client.pem', // 默认不使用客户端证书,自API 11开始支持该属性keyPath: '/path/to/client.key', // 若证书包含Key信息,传入空字符串,自API 11开始支持该属性certType: http.CertType.PEM, // 可选,默认使用PEM,自API 11开始支持该属性keyPassword: "passwordToKey" // 可选,输入key文件的密码,自API 11开始支持该属性},multiFormDataList: [ // 可选,仅当Header中,'content-Type'为'multipart/form-data'时生效,自API 11开始支持该属性{name: "Part1", // 数据名,自API 11开始支持该属性contentType: 'text/plain', // 数据类型,自API 11开始支持该属性data: 'Example data', // 可选,数据内容,自API 11开始支持该属性remoteFileName: 'example.txt' // 可选,自API 11开始支持该属性}, {name: "Part2", // 数据名,自API 11开始支持该属性contentType: 'text/plain', // 数据类型,自API 11开始支持该属性// data/app/el2/100/base/com.example.myapplication/haps/entry/files/fileName.txtfilePath: `${getContext(this).filesDir}/fileName.txt`, // 可选,传入文件路径,自API 11开始支持该属性remoteFileName: 'fileName.txt' // 可选,自API 11开始支持该属性}]}, (err: BusinessError, data: http.HttpResponse) => {if (!err) {// data.result为HTTP响应内容,可根据业务需要进行解析console.info('Result:' + JSON.stringify(data.result));console.info('code:' + JSON.stringify(data.responseCode));// data.header为HTTP响应头,可根据业务需要进行解析console.info('header:' + JSON.stringify(data.header));console.info('cookies:' + JSON.stringify(data.cookies)); // 8+// 当该请求使用完毕时,调用destroy方法主动销毁httpRequest.destroy();} else {console.error('error:' + JSON.stringify(err));// 取消订阅HTTP响应头事件httpRequest.off('headersReceive');// 当该请求使用完毕时,调用destroy方法主动销毁httpRequest.destroy();}});
除了普通的request()接口外,API 10 及以后我们还可以使用requestInStream()接口,来实现网络请求的流式响应。
👉🏻 开发步骤如下:

实例代码如下:
// 引入包名import { http } from '@kit.NetworkKit';import { BusinessError } from '@kit.BasicServicesKit';// 每一个httpRequest对应一个HTTP请求任务,不可复用let httpRequest = http.createHttp();// 用于订阅HTTP响应头事件httpRequest.on('headersReceive', (header: Object) => {console.info('header: ' + JSON.stringify(header));});// 用于订阅HTTP流式响应数据接收事件let res = new ArrayBuffer(0);httpRequest.on('dataReceive', (data: ArrayBuffer) => {const newRes = new ArrayBuffer(res.byteLength + data.byteLength);const resView = new Uint8Array(newRes);resView.set(new Uint8Array(res));resView.set(new Uint8Array(data), res.byteLength);res = newRes;console.info('res length: ' + res.byteLength);});// 用于订阅HTTP流式响应数据接收完毕事件httpRequest.on('dataEnd', () => {console.info('No more data in response, data receive end');});// 用于订阅HTTP流式响应数据接收进度事件class Data {receiveSize: number = 0;totalSize: number = 0;}httpRequest.on('dataReceiveProgress', (data: Data) => {console.log("dataReceiveProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);});let streamInfo: http.HttpRequestOptions = {method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET// 开发者根据自身业务需要添加header字段header: {'Content-Type': 'application/json'},// 当使用POST请求时此字段用于传递请求体内容,具体格式与服务端协商确定extraData: "data to send",expectDataType: http.HttpDataType.STRING,// 可选,指定返回数据的类型usingCache: true, // 可选,默认为truepriority: 1, // 可选,默认为1connectTimeout: 60000, // 可选,默认为60000msreadTimeout: 60000, // 可选,默认为60000ms。若传输的数据较大,需要较长的时间,建议增大该参数以保证数据传输正常终止usingProtocol: http.HttpProtocol.HTTP1_1 // 可选,协议类型默认值由系统自动指定}// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定httpRequest.requestInStream("EXAMPLE_URL", streamInfo).then((data: number) => {console.info("requestInStream OK!");console.info('ResponseCode :' + JSON.stringify(data));// 取消订阅HTTP响应头事件httpRequest.off('headersReceive');// 取消订阅HTTP流式响应数据接收事件httpRequest.off('dataReceive');// 取消订阅HTTP流式响应数据接收进度事件httpRequest.off('dataReceiveProgress');// 取消订阅HTTP流式响应数据接收完毕事件httpRequest.off('dataEnd');// 当该请求使用完毕时,调用destroy方法主动销毁httpRequest.destroy();}).catch((err: Error) => {console.info("requestInStream ERROR : err = " + JSON.stringify(err));});
3、WebSocket连接
使用WebSocket建立服务器与客户端的双向连接,需要先通过createWebSocket()方法创建WebSocket对象,然后通过connect()方法连接到服务器。当连接成功后,客户端会收到open事件的回调,之后客户端就可以通过send()方法与服务器进行通信。当服务器发信息给客户端时,客户端会收到message事件的回调。当客户端不要此连接时,可以通过调用close()方法主动断开连接,之后客户端会收到close事件的回调。
【使用该功能需要申请ohos.permission.INTERNET权限】
【若在上述任一过程中发生错误,客户端会收到error事件的回调】
WebSocket连接功能主要由webSocket模块提供,具体接口说明如下:

一般情况下,常见的开发步骤如下:
-
导入需要的webSocket模块。
-
创建一个WebSocket连接,返回一个WebSocket对象。
-
(可选)订阅WebSocket的打开、消息接收、关闭、Error事件。
-
根据URL地址,发起WebSocket连接。
-
使用完WebSocket连接之后,主动断开连接。
import { webSocket } from '@kit.NetworkKit';import { BusinessError } from '@kit.BasicServicesKit';let defaultIpAddress = "ws://";let ws = webSocket.createWebSocket();ws.on('open', (err: BusinessError, value: Object) => {console.log("on open, status:" + JSON.stringify(value));// 当收到on('open')事件时,可以通过send()方法与服务器进行通信ws.send("Hello, server!", (err: BusinessError, value: boolean) => {if (!err) {console.log("Message sent successfully");} else {console.log("Failed to send the message. Err:" + JSON.stringify(err));}});});ws.on('message', (err: BusinessError, value: string | ArrayBuffer) => {console.log("on message, message:" + value);// 当收到服务器的`bye`消息时(此消息字段仅为示意,具体字段需要与服务器协商),主动断开连接if (value === 'bye') {ws.close((err: BusinessError, value: boolean) => {if (!err) {console.log("Connection closed successfully");} else {console.log("Failed to close the connection. Err: " + JSON.stringify(err));}});}});ws.on('close', (err: BusinessError, value: webSocket.CloseResult) => {console.log("on close, code is " + value.code + ", reason is " + value.reason);});ws.on('error', (err: BusinessError) => {console.log("on error, error:" + JSON.stringify(err));});ws.connect(defaultIpAddress, (err: BusinessError, value: boolean) => {if (!err) {console.log("Connected successfully");} else {console.log("Connection failed. Err:" + JSON.stringify(err));}});



















