1# @ohos.net.connection (网络连接管理)
2
3网络连接管理提供管理网络一些基础能力,包括获取默认激活的数据网络、获取所有激活数据网络列表、开启关闭飞行模式、获取网络能力信息等功能。
4
5> **说明:**
6>
7> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8> 无特殊说明,接口默认不支持并发。
9
10## 导入模块
11
12```ts
13import { connection } from '@kit.NetworkKit';
14```
15
16## connection.createNetConnection
17
18createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
19
20创建一个NetConnection对象,[netSpecifier](#netspecifier)指定关注的网络的各项特征;timeout是超时时间(单位是毫秒);netSpecifier是timeout的必要条件,两者都没有则表示关注默认网络。
21
22**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
23
24**系统能力**:SystemCapability.Communication.NetManager.Core
25
26**参数:**
27
28| 参数名       | 类型                          | 必填 | 说明                                                         |
29| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
30| netSpecifier | [NetSpecifier](#netspecifier) | 否   | 指定网络的各项特征,不指定或为undefined时关注默认网络。                   |
31| timeout      | number                        | 否   | 获取netSpecifier指定的网络时的超时时间,仅netSpecifier存在时生效,undefined时默认值为0。 |
32
33**返回值:**
34
35| 类型                            | 说明                 |
36| ------------------------------- | -------------------- |
37| [NetConnection](#netconnection) | 所关注的网络的句柄。 |
38
39**示例:**
40
41```ts
42import { connection } from '@kit.NetworkKit';
43
44// 关注默认网络, 不需要传参
45let netConnection = connection.createNetConnection();
46
47// 关注蜂窝网络,需要传入相关网络特征,timeout参数未传入说明未使用超时时间,此时timeout为0
48let netConnectionCellular = connection.createNetConnection({
49  netCapabilities: {
50    bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
51  }
52});
53```
54
55## connection.getDefaultNet
56
57getDefaultNet(callback: AsyncCallback\<NetHandle>): void
58
59获取默认激活的数据网络,使用callback方式作为异步方法。可以使用[getNetCapabilities](#connectiongetnetcapabilities)去获取网络的类型、拥有的能力等信息。
60
61**需要权限**:ohos.permission.GET_NETWORK_INFO
62
63**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
64
65**系统能力**:SystemCapability.Communication.NetManager.Core
66
67**参数:**
68
69| 参数名   | 类型                                    | 必填 | 说明                                                         |
70| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
71| callback | AsyncCallback\<[NetHandle](#nethandle)> | 是   | 回调函数。当成功获取默认激活的数据网络时,error为undefined,data为默认激活的数据网络;否则为错误对象。 |
72
73**错误码:**
74
75以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
76
77| 错误码ID | 错误信息                        |
78| ------- | -----------------------------  |
79| 201     | Permission denied.             |
80| 401     | Parameter error.                 |
81| 2100002 | Failed to connect to the service. |
82| 2100003 | System internal error.         |
83
84**示例:**
85
86```ts
87import { connection } from '@kit.NetworkKit';
88import { BusinessError } from '@kit.BasicServicesKit';
89
90connection.getDefaultNet((error: BusinessError, data: connection.NetHandle) => {
91  if (error) {
92    console.error(`Failed to get default net. Code:${error.code}, message:${error.message}`);
93    return;
94  }
95  console.info("Succeeded to get data " + JSON.stringify(data));
96});
97```
98
99## connection.getDefaultNet
100
101getDefaultNet(): Promise\<NetHandle>
102
103获取默认激活的数据网络,使用Promise方式作为异步方法。可以使用[getNetCapabilities](#connectiongetnetcapabilities)去获取网络的类型、拥有的能力等信息。
104
105**需要权限**:ohos.permission.GET_NETWORK_INFO
106
107**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
108
109**系统能力**:SystemCapability.Communication.NetManager.Core
110
111**返回值:**
112
113| 类型                              | 说明                                  |
114| --------------------------------- | ------------------------------------- |
115| Promise\<[NetHandle](#nethandle)> | 以Promise形式返回默认激活的数据网络。 |
116
117**错误码:**
118
119以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
120
121| 错误码ID | 错误信息                         |
122| ------- | -------------------------------- |
123| 201     | Permission denied.               |
124| 2100002 | Failed to connect to the service.|
125| 2100003 | System internal error.           |
126
127**示例:**
128
129```ts
130import { connection } from '@kit.NetworkKit';
131
132connection.getDefaultNet().then((data: connection.NetHandle) => {
133  console.info("Succeeded to get data: " + JSON.stringify(data));
134});
135```
136
137## connection.getDefaultNetSync<sup>9+</sup>
138
139getDefaultNetSync(): NetHandle
140
141使用同步方法获取默认激活的数据网络。可以使用[getNetCapabilities](#connectiongetnetcapabilities)去获取网络的类型、拥有的能力等信息。
142
143**需要权限**:ohos.permission.GET_NETWORK_INFO
144
145**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
146
147**系统能力**:SystemCapability.Communication.NetManager.Core
148
149**返回值:**
150
151| 类型      | 说明                               |
152| --------- | ---------------------------------- |
153| [NetHandle](#nethandle) | 以同步方式返回默认激活的数据网络。 |
154
155**错误码:**
156
157以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
158
159| 错误码ID | 错误信息                         |
160| ------- | -------------------------------- |
161| 201     | Permission denied.               |
162| 2100002 | Failed to connect to the service.|
163| 2100003 | System internal error.           |
164
165**示例:**
166
167```ts
168import { connection } from '@kit.NetworkKit';
169
170let netHandle = connection.getDefaultNetSync();
171```
172
173
174## connection.setAppHttpProxy<sup>11+</sup>
175
176setAppHttpProxy(httpProxy: HttpProxy): void
177
178设置网络应用级Http代理配置信息。
179
180**系统能力**:SystemCapability.Communication.NetManager.Core
181
182**参数:**
183
184| 参数名    | 类型                                                         | 必填 | 说明             |
185| --------- | ------------------------------------------------------------ | ---- | ---------------- |
186| httpProxy | [HttpProxy](#httpproxy10)                                      | 是   | 网络应用级Http代理配置信息。 |
187
188**错误码:**
189
190以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
191
192| 错误码ID | 错误信息                       |
193| ------- | -----------------------------  |
194| 401     | Parameter error.               |
195| 2100001 | Invalid http proxy.            |
196
197**示例:**
198
199```ts
200import { connection } from '@kit.NetworkKit';
201import { BusinessError } from '@kit.BasicServicesKit';
202
203let exclusionStr = "192.168,baidu.com";
204let exclusionArray = exclusionStr.split(',');
205connection.setAppHttpProxy({
206  host: "192.168.xx.xxx",
207  port: 8080,
208  exclusionList: exclusionArray
209} as connection.HttpProxy);
210```
211
212**预置锁定证书PIN:**
213
214证书PIN是对证书文件用sha256算法计算出的hash值。
215对于证书server.pem, 可以用如下openssl命令计算它的PIN:
216
217```shell
218cat server.pem \
219| sed -n '/-----BEGIN/,/-----END/p' \
220| openssl x509 -noout -pubkey \
221| openssl pkey -pubin -outform der \
222| openssl dgst -sha256 -binary \
223| openssl enc -base64
224```
225
226**预置应用级证书:**
227
228直接把证书原文件预置在APP中。目前支持crt和pem格式的证书文件。
229
230**注意:**
231
232当前ohos.net.http和Image组件的证书锁定,会匹配证书链上所有证书的哈希值,如果服务器更新了任意一本证书,都会导致校验失败。如果服务器出现了更新证书的情况,APP版本应当随之更新并推荐消费者尽快升级APP版本,否则可能导致联网失败。
233
234**预置JSON配置文件:**
235
236预置的证书与网络服务器的对应关系通过JSON配置。
237配置文件在APP中的路径是:src/main/resources/base/profile/network_config.json
238
239**JSON配置文件:**
240
241证书锁定的配置例子如下:
242```json
243{
244  "network-security-config": {
245    "domain-config": [
246      {
247        "domains": [
248          {
249            "include-subdomains": true,
250            "name": "server.com"
251          }
252        ],
253        "pin-set": {
254          "expiration": "2024-11-08",
255          "pin": [
256            {
257              "digest-algorithm": "sha256",
258              "digest": "FEDCBA987654321"
259            }
260          ]
261        }
262      }
263    ]
264  },
265  "trust-global-user-ca": false,
266  "trust-current-user-ca": false,
267}
268```
269
270应用级证书的配置例子如下:
271```json
272{
273  "network-security-config": {
274    "base-config": {
275      "trust-anchors": [
276        {
277          "certificates": "/etc/security/certificates"
278        }
279      ]
280    },
281    "domain-config": [
282      {
283        "domains": [
284          {
285            "include-subdomains": true,
286            "name": "example.com"
287          }
288        ],
289        "trust-anchors": [
290          {
291            "certificates": "/data/storage/el1/bundle/entry/resources/resfile"
292          }
293        ]
294      }
295    ]
296  }
297}
298
299```
300
301**各个字段含义:**
302
303**network-security-config(object:网络安全配置)**
304
305可包含0或者1个base-config
306
307必须包含1个domain-config
308
309**trust-global-user-ca: 是否信任企业MDM系统或设备管理员用户手动安装的CA证书,默认true**
310
311**trust-current-user-ca: 是否信任当前用户安装的证书,默认true**
312
313**base-config(object:指示应用程序范围的安全配置)**
314
315必须包含1个trust-anchors
316
317**domain-config(array:指示每个域的安全配置)**
318
319可以包含任意个item
320
321item必须包含1个domain
322
323item可以包含0或者1个trust-anchors
324
325item可包含0个或者1个pin-set
326
327**trust-anchors(array:受信任的CA)**
328
329可以包含任意个item
330
331item必须包含1个certificates(string:CA证书路径)
332
333**domain(array:域)**
334
335可以包含任意个item
336
337item必须包含1个name(string:指示域名)
338
339item可以包含0或者1个include-subdomains(boolean:指示规则是否适用于子域)
340
341**pin-set(object:证书PIN设置)**
342
343必须包含1个pin
344
345可以包含0或者1个expiration(string:指示证书PIN的过期时间)
346
347**pin(array:证书PIN)**
348
349可以包含任意个item
350
351item必须包含1个digest-algorithm(string:指示用于生成pin的摘要算法)
352
353item必须包含1个digest(string:指示公钥PIN)
354
355## connection.getDefaultHttpProxy<sup>10+</sup>
356
357getDefaultHttpProxy(callback: AsyncCallback\<HttpProxy>): void
358
359获取网络默认的代理配置信息。
360如果设置了全局代理,则会返回全局代理配置信息。如果进程使用[setAppNet](#connectionsetappnet9)绑定到指定[NetHandle](#nethandle)对应的网络,则返回[NetHandle](#nethandle)对应网络的代理配置信息。在其它情况下,将返回默认网络的代理配置信息。
361使用callback方式作为异步方法。
362
363**系统能力**:SystemCapability.Communication.NetManager.Core
364
365**参数:**
366
367| 参数名   | 类型                                   | 必填 | 说明                                                         |
368| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
369| callback | AsyncCallback<[HttpProxy](#httpproxy10)> | 是   | 回调函数。当成功获取网络默认的代理配置信息时,error为undefined,data为网络默认的代理配置信息;否则为错误对象。 |
370
371**错误码:**
372
373以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
374
375| 错误码ID | 错误信息                                     |
376| -------- | -------------------------------------------- |
377| 2100002  | Failed to connect to the service.            |
378| 2100003  | System internal error.                       |
379
380**示例:**
381
382```ts
383import { connection } from '@kit.NetworkKit';
384import { BusinessError } from '@kit.BasicServicesKit';
385
386connection.getDefaultHttpProxy((error: BusinessError, data: connection.HttpProxy) => {
387  if (error) {
388    console.error(`Failed to get default http proxy. Code:${error.code}, message:${error.message}`);
389    return;
390  }
391  console.log("Succeeded to get data" + JSON.stringify(data));
392});
393```
394
395## connection.getDefaultHttpProxy<sup>10+</sup>
396
397getDefaultHttpProxy(): Promise\<HttpProxy>
398
399获取网络默认的代理配置信息。
400如果设置了全局代理,则会返回全局代理配置信息。如果进程使用[setAppNet](#connectionsetappnet9)绑定到指定[NetHandle](#nethandle)对应的网络,则返回[NetHandle](#nethandle)对应网络的代理配置信息。在其它情况下,将返回默认网络的代理配置信息。
401使用Promise方式作为异步方法。
402
403**系统能力**:SystemCapability.Communication.NetManager.Core
404
405**返回值:**
406
407| 类型                             | 说明                                      |
408| -------------------------------- | ----------------------------------------- |
409| Promise<[HttpProxy](#httpproxy10)> | 以Promise形式返回网络默认的代理配置信息。 |
410
411**错误码:**
412
413以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
414
415| 错误码ID | 错误信息                                     |
416| -------- | -------------------------------------------- |
417| 2100002  | Failed to connect to the service.            |
418| 2100003  | System internal error.                       |
419
420**示例:**
421
422```ts
423import { connection } from '@kit.NetworkKit';
424import { BusinessError } from '@kit.BasicServicesKit';
425
426connection.getDefaultHttpProxy().then((data: connection.HttpProxy) => {
427  console.info(JSON.stringify(data));
428}).catch((error: BusinessError) => {
429  console.info(JSON.stringify(error));
430});
431```
432
433## connection.getAppNet<sup>9+</sup>
434
435getAppNet(callback: AsyncCallback\<NetHandle>): void
436
437获取App绑定的网络信息,使用callback方式作为异步方法。
438
439**系统能力**:SystemCapability.Communication.NetManager.Core
440
441**参数:**
442
443| 参数名   | 类型                                    | 必填 | 说明                                                         |
444| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
445| callback | AsyncCallback\<[NetHandle](#nethandle)> | 是   | 回调函数。当成功获取App绑定的网络信息时,error为undefined,data为获取到App绑定的网络信息;否则为错误对象。 |
446
447**错误码:**
448
449以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
450
451| 错误码ID | 错误信息                        |
452| ------- | -----------------------------  |
453| 401     | Parameter error.                 |
454| 2100002 | Failed to connect to the service.|
455| 2100003 | System internal error.         |
456
457**示例:**
458
459```ts
460import { connection } from '@kit.NetworkKit';
461import { BusinessError } from '@kit.BasicServicesKit';
462
463connection.getAppNet((error: BusinessError, data: connection.NetHandle) => {
464  if (error) {
465    console.error(`Failed to get app net. Code:${error.code}, message:${error.message}`);
466    return;
467  }
468  console.info("Succeeded to get data: " + JSON.stringify(data));
469})
470```
471
472## connection.getAppNet<sup>9+</sup>
473
474getAppNet(): Promise\<NetHandle>
475
476获取App绑定的网络信息,使用Promise方式作为异步方法。
477
478**系统能力**:SystemCapability.Communication.NetManager.Core
479
480**返回值:**
481
482| 类型                              | 说明                                  |
483| --------------------------------- | ------------------------------------- |
484| Promise\<[NetHandle](#nethandle)> | 以Promise形式返回App绑定的网络信息。 |
485
486**错误码:**
487
488以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
489
490| 错误码ID | 错误信息                        |
491| ------- | -----------------------------  |
492| 2100002 | Failed to connect to the service.|
493| 2100003 | System internal error.         |
494
495**示例:**
496
497```ts
498import { connection } from '@kit.NetworkKit';
499import { BusinessError } from '@kit.BasicServicesKit';
500
501connection.getAppNet().then((data: connection.NetHandle) => {
502  console.info(JSON.stringify(data));
503}).catch((error: BusinessError) => {
504  console.info(JSON.stringify(error));
505});
506```
507
508## connection.getAppNetSync<sup>10+</sup>
509
510getAppNetSync(): NetHandle
511
512使用同步方法获取App绑定的网络信息。
513
514**系统能力**:SystemCapability.Communication.NetManager.Core
515
516**返回值:**
517
518| 类型      | 说明                               |
519| --------- | ---------------------------------- |
520| [NetHandle](#nethandle) | 返回APP绑定的数据网络。 |
521
522**错误码:**
523
524以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
525
526| 错误码ID | 错误信息                        |
527| ------- | -----------------------------  |
528| 2100002 | Failed to connect to the service.|
529| 2100003 | System internal error.         |
530
531**示例:**
532
533```ts
534import { connection } from '@kit.NetworkKit';
535
536let netHandle = connection.getAppNetSync();
537```
538
539## connection.setAppNet<sup>9+</sup>
540
541setAppNet(netHandle: NetHandle, callback: AsyncCallback\<void>): void
542
543绑定App到指定网络,绑定后的App只能通过指定网络访问外网,使用callback方式作为异步方法。
544
545**需要权限**:ohos.permission.INTERNET
546
547**系统能力**:SystemCapability.Communication.NetManager.Core
548
549**参数:**
550
551| 参数名    | 类型                    | 必填 | 说明                                                         |
552| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
553| netHandle | [NetHandle](#nethandle) | 是   | 数据网络的句柄。                                             |
554| callback  | AsyncCallback\<void>    | 是   | 回调函数。当成功绑定App到指定网络时,error为undefined,否则为错误对象。|
555
556**错误码:**
557
558以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
559
560| 错误码ID | 错误信息                        |
561| ------- | -----------------------------  |
562| 201     | Permission denied.             |
563| 401     | Parameter error.               |
564| 2100001 | Invalid parameter value.                |
565| 2100002 | Failed to connect to the service.|
566| 2100003 | System internal error.         |
567
568**示例:**
569
570```ts
571import { connection } from '@kit.NetworkKit';
572import { BusinessError } from '@kit.BasicServicesKit';
573
574connection.getDefaultNet((error: BusinessError, netHandle: connection.NetHandle) => {
575  if (netHandle.netId == 0) {
576    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
577    return;
578  }
579  connection.setAppNet(netHandle, (error: BusinessError, data: void) => {
580    if (error) {
581      console.error(`Failed to get default net. Code:${error.code}, message:${error.message}`);
582      return;
583    }
584    console.info("Succeeded to get data: " + JSON.stringify(data));
585  });
586});
587```
588
589## connection.setAppNet<sup>9+</sup>
590
591setAppNet(netHandle: NetHandle): Promise\<void>
592
593绑定App到指定网络,绑定后的App只能通过指定网络访问外网,使用Promise方式作为异步方法。
594
595**需要权限**:ohos.permission.INTERNET
596
597**系统能力**:SystemCapability.Communication.NetManager.Core
598
599**参数:**
600
601| 参数名    | 类型                                                         | 必填 | 说明             |
602| --------- | ------------------------------------------------------------ | ---- | ---------------- |
603| netHandle | [NetHandle](#nethandle)                                      | 是   | 数据网络的句柄。 |
604
605**返回值:**
606
607| 类型                                        | 说明                          |
608| ------------------------------------------- | ----------------------------- |
609| Promise\<void> | 无返回值的Promise对象。 |
610
611**错误码:**
612
613以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
614
615| 错误码ID | 错误信息                        |
616| ------- | -----------------------------  |
617| 201     | Permission denied.             |
618| 401     | Parameter error.               |
619| 2100001 | Invalid parameter value.                |
620| 2100002 | Failed to connect to the service.|
621| 2100003 | System internal error.         |
622
623**示例:**
624
625```ts
626import { connection } from '@kit.NetworkKit';
627import { BusinessError } from '@kit.BasicServicesKit';
628
629connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
630  if (netHandle.netId == 0) {
631    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
632    return;
633  }
634
635  connection.setAppNet(netHandle).then(() => {
636    console.log("success");
637  }).catch((error: BusinessError) => {
638    console.log(JSON.stringify(error));
639  })
640});
641```
642
643## connection.getAllNets
644
645getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void
646
647获取所有处于连接状态的网络列表,使用callback方式作为异步方法。
648
649**需要权限**:ohos.permission.GET_NETWORK_INFO
650
651**系统能力**:SystemCapability.Communication.NetManager.Core
652
653**参数:**
654
655| 参数名 | 类型 | 必填 | 说明 |
656| -------- | -------- | -------- | -------- |
657| callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | 是 | 回调函数。当成功获取所有处于连接状态的网络列表时,error为undefined,data为激活的数据网络列表;否则为错误对象。|
658
659**错误码:**
660
661以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
662
663| 错误码ID | 错误信息                        |
664| ------- | -----------------------------  |
665| 201     | Permission denied.             |
666| 401     | Parameter error.                 |
667| 2100002 | Failed to connect to the service.|
668| 2100003 | System internal error.         |
669
670**示例:**
671
672```ts
673import { connection } from '@kit.NetworkKit';
674import { BusinessError } from '@kit.BasicServicesKit';
675
676connection.getAllNets((error: BusinessError, data: connection.NetHandle[]) => {
677  if (error) {
678    console.error(`Failed to get all nets. Code:${error.code}, message:${error.message}`);
679    return;
680  }
681  console.info("Succeeded to get data: " + JSON.stringify(data));
682});
683```
684
685## connection.getAllNets
686
687getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt;
688
689获取所有处于连接状态的网络列表,使用Promise方式作为异步方法。
690
691**需要权限**:ohos.permission.GET_NETWORK_INFO
692
693**系统能力**:SystemCapability.Communication.NetManager.Core
694
695**返回值:**
696
697| 类型 | 说明 |
698| -------- | -------- |
699| Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | 以Promise形式返回激活的数据网络列表。 |
700
701**错误码:**
702
703以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
704
705| 错误码ID | 错误信息                        |
706| ------- | -----------------------------  |
707| 201     | Permission denied.             |
708| 2100002 | Failed to connect to the service.|
709| 2100003 | System internal error.         |
710
711**示例:**
712
713```ts
714import { connection } from '@kit.NetworkKit';
715
716connection.getAllNets().then((data: connection.NetHandle[]) => {
717  console.info("Succeeded to get data: " + JSON.stringify(data));
718});
719```
720
721## connection.getAllNetsSync<sup>10+</sup>
722
723getAllNetsSync(): Array&lt;NetHandle&gt;
724
725使用同步方法获取所有处于连接状态的网络列表。
726
727**需要权限**:ohos.permission.GET_NETWORK_INFO
728
729**系统能力**:SystemCapability.Communication.NetManager.Core
730
731**返回值:**
732
733| 类型      | 说明                               |
734| --------- | ---------------------------------- |
735| Array&lt;[NetHandle](#nethandle)&gt; | 返回激活的数据网络列表。 |
736
737**错误码:**
738
739以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
740
741| 错误码ID | 错误信息                        |
742| ------- | -----------------------------  |
743| 201     | Permission denied.             |
744| 2100002 | Failed to connect to the service.|
745| 2100003 | System internal error.         |
746
747**示例:**
748
749```ts
750import { connection } from '@kit.NetworkKit';
751
752let netHandle = connection.getAllNetsSync();
753```
754
755## connection.getConnectionProperties
756
757getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void
758
759获取netHandle对应的网络的连接信息,使用callback方式作为异步方法。
760
761**需要权限**:ohos.permission.GET_NETWORK_INFO
762
763**系统能力**:SystemCapability.Communication.NetManager.Core
764
765**参数:**
766
767| 参数名    | 类型                                                         | 必填 | 说明                                                         |
768| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
769| netHandle | [NetHandle](#nethandle)                                      | 是   | 数据网络的句柄。                                             |
770| callback  | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | 是   | 回调函数。当成功获取netHandle对应的网络的连接信息时,error为undefined,data为获取的网络连接信息;否则为错误对象。|
771
772**错误码:**
773
774以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
775
776| 错误码ID | 错误信息                        |
777| ------- | -----------------------------  |
778| 201     | Permission denied.             |
779| 401     | Parameter error.               |
780| 2100001 | Invalid parameter value.                |
781| 2100002 | Failed to connect to the service.|
782| 2100003 | System internal error.         |
783
784**示例:**
785
786```ts
787import { connection } from '@kit.NetworkKit';
788import { BusinessError } from '@kit.BasicServicesKit';
789
790connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
791  if (netHandle.netId == 0) {
792    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
793    return;
794  }
795  connection.getConnectionProperties(netHandle, (error: BusinessError, data: connection.ConnectionProperties) => {
796    if (error) {
797      console.error(`Failed to get connection properties. Code:${error.code}, message:${error.message}`);
798      return;
799    }
800    console.info("Succeeded to get data: " + JSON.stringify(data));
801  })
802});
803```
804
805## connection.getConnectionProperties
806
807getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties>
808
809获取netHandle对应的网络的连接信息,使用Promise方式作为异步方法。
810
811**需要权限**:ohos.permission.GET_NETWORK_INFO
812
813**系统能力**:SystemCapability.Communication.NetManager.Core
814
815**参数:**
816
817| 参数名    | 类型                    | 必填 | 说明             |
818| --------- | ----------------------- | ---- | ---------------- |
819| netHandle | [NetHandle](#nethandle) | 是   | 数据网络的句柄。 |
820
821**返回值:**
822
823| 类型                                                    | 说明                              |
824| ------------------------------------------------------- | --------------------------------- |
825| Promise\<[ConnectionProperties](#connectionproperties)> | 以Promise形式返回网络的连接信息。 |
826
827**错误码:**
828
829以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
830
831| 错误码ID | 错误信息                        |
832| ------- | -----------------------------  |
833| 201     | Permission denied.             |
834| 401     | Parameter error.               |
835| 2100001 | Invalid parameter value.                |
836| 2100002 | Failed to connect to the service.|
837| 2100003 | System internal error.         |
838
839**示例:**
840
841```ts
842import { connection } from '@kit.NetworkKit';
843
844connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
845  if (netHandle.netId == 0) {
846    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
847    return;
848  }
849
850  connection.getConnectionProperties(netHandle).then((data: connection.ConnectionProperties) => {
851    console.info("Succeeded to get data: " + JSON.stringify(data));
852  })
853});
854```
855
856## connection.getConnectionPropertiesSync<sup>10+</sup>
857
858getConnectionPropertiesSync(netHandle: NetHandle): ConnectionProperties
859
860获取netHandle对应的网络的连接信息,使用同步方法返回。
861
862**需要权限**:ohos.permission.GET_NETWORK_INFO
863
864**系统能力**:SystemCapability.Communication.NetManager.Core
865
866**参数:**
867
868| 参数名    | 类型                    | 必填 | 说明             |
869| --------- | ----------------------- | ---- | ---------------- |
870| netHandle | [NetHandle](#nethandle) | 是   | 数据网络的句柄。 |
871
872**返回值:**
873
874| 类型                                                    | 说明                              |
875| ------------------------------------------------------- | --------------------------------- |
876| [ConnectionProperties](#connectionproperties) | 返回网络的连接信息。 |
877
878**错误码:**
879
880以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
881
882| 错误码ID | 错误信息                        |
883| ------- | -----------------------------  |
884| 201     | Permission denied.             |
885| 401     | Parameter error.               |
886| 2100001 | Invalid parameter value.                |
887| 2100002 | Failed to connect to the service.|
888| 2100003 | System internal error.         |
889
890**示例:**
891
892```ts
893import { connection } from '@kit.NetworkKit';
894import { BusinessError } from '@kit.BasicServicesKit';
895
896let netHandle: connection.NetHandle;
897let connectionproperties: connection.ConnectionProperties;
898
899connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
900  if (netHandle.netId == 0) {
901    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
902    return;
903  }
904  netHandle = connection.getDefaultNetSync();
905  connectionproperties = connection.getConnectionPropertiesSync(netHandle);
906  console.info("Succeeded to get connectionproperties: " + JSON.stringify(connectionproperties));
907});
908
909```
910
911## connection.getNetCapabilities
912
913getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void
914
915获取netHandle对应的网络的能力信息,使用callback方式作为异步方法。
916
917**需要权限**:ohos.permission.GET_NETWORK_INFO
918
919**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
920
921**系统能力**:SystemCapability.Communication.NetManager.Core
922
923**参数:**
924
925| 参数名    | 类型                                                | 必填 | 说明                                                         |
926| --------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ |
927| netHandle | [NetHandle](#nethandle)                             | 是   | 数据网络的句柄。                                             |
928| callback  | AsyncCallback\<[NetCapabilities](#netcapabilities)> | 是   | 回调函数。当成功获取netHandle对应的网络的能力信息时,error为undefined,data为获取到的网络能力信息;否则为错误对象。|
929
930**错误码:**
931
932以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
933
934| 错误码ID | 错误信息                        |
935| ------- | -----------------------------  |
936| 201     | Permission denied.             |
937| 401     | Parameter error.               |
938| 2100001 | Invalid parameter value.                |
939| 2100002 | Failed to connect to the service.|
940| 2100003 | System internal error.         |
941
942**示例:**
943
944```ts
945import { connection } from '@kit.NetworkKit';
946import { BusinessError } from '@kit.BasicServicesKit';
947
948connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
949  if (netHandle.netId == 0) {
950    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
951    return;
952  }
953  connection.getNetCapabilities(netHandle, (error: BusinessError, data: connection.NetCapabilities) => {
954    if (error) {
955      console.error(`Failed to get net capabilities. Code:${error.code}, message:${error.message}`);
956      return;
957    }
958    console.info("Succeeded to get data: " + JSON.stringify(data));
959  })
960}).catch((error: BusinessError) => {
961    console.error(JSON.stringify(error));
962});
963```
964
965## connection.getNetCapabilities
966
967getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities>
968
969获取netHandle对应的网络的能力信息,使用Promise方式作为异步方法。
970
971**需要权限**:ohos.permission.GET_NETWORK_INFO
972
973**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
974
975**系统能力**:SystemCapability.Communication.NetManager.Core
976
977**参数:**
978
979| 参数名    | 类型                    | 必填 | 说明             |
980| --------- | ----------------------- | ---- | ---------------- |
981| netHandle | [NetHandle](#nethandle) | 是   | 数据网络的句柄。 |
982
983**返回值:**
984
985| 类型                                          | 说明                              |
986| --------------------------------------------- | --------------------------------- |
987| Promise\<[NetCapabilities](#netcapabilities)> | 以Promise形式返回网络的能力信息。 |
988
989**错误码:**
990
991以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
992
993| 错误码ID | 错误信息                        |
994| ------- | -----------------------------  |
995| 201     | Permission denied.             |
996| 401     | Parameter error.               |
997| 2100001 | Invalid parameter value.                |
998| 2100002 | Failed to connect to the service.|
999| 2100003 | System internal error.         |
1000
1001**示例:**
1002
1003```ts
1004import { connection } from '@kit.NetworkKit';
1005
1006connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
1007  if (netHandle.netId == 0) {
1008    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
1009    return;
1010  }
1011  connection.getNetCapabilities(netHandle).then((data: connection.NetCapabilities) => {
1012      console.info("Succeeded to get data: " + JSON.stringify(data));
1013  })
1014}).catch((error: BusinessError) => {
1015    console.error(JSON.stringify(error));
1016});
1017```
1018
1019## connection.getNetCapabilitiesSync<sup>10+</sup>
1020
1021getNetCapabilitiesSync(netHandle: NetHandle): NetCapabilities
1022
1023获取netHandle对应的网络的能力信息,使用同步方式返回。
1024
1025**需要权限**:ohos.permission.GET_NETWORK_INFO
1026
1027**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1028
1029**系统能力**:SystemCapability.Communication.NetManager.Core
1030
1031**参数:**
1032
1033| 参数名    | 类型                    | 必填 | 说明             |
1034| --------- | ----------------------- | ---- | ---------------- |
1035| netHandle | [NetHandle](#nethandle) | 是   | 数据网络的句柄。 |
1036
1037**返回值:**
1038
1039| 类型                                          | 说明                              |
1040| --------------------------------------------- | --------------------------------- |
1041| [NetCapabilities](#netcapabilities) | 返回网络的能力信息。 |
1042
1043**错误码:**
1044
1045以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1046
1047| 错误码ID | 错误信息                        |
1048| ------- | -----------------------------  |
1049| 201     | Permission denied.             |
1050| 401     | Parameter error.               |
1051| 2100001 | Invalid parameter value.                |
1052| 2100002 | Failed to connect to the service.|
1053| 2100003 | System internal error.         |
1054
1055**示例:**
1056
1057```ts
1058import { connection } from '@kit.NetworkKit';
1059import { BusinessError } from '@kit.BasicServicesKit';
1060
1061let netHandle: connection.NetHandle;
1062let getNetCapabilitiesSync: connection.NetCapabilities;
1063
1064connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
1065  if (netHandle.netId == 0) {
1066    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
1067    return;
1068  }
1069
1070  getNetCapabilitiesSync = connection.getNetCapabilitiesSync(netHandle);
1071  console.info("Succeeded to get net capabilities sync: " + JSON.stringify(getNetCapabilitiesSync));
1072});
1073
1074```
1075
1076## connection.isDefaultNetMetered<sup>9+</sup>
1077
1078isDefaultNetMetered(callback: AsyncCallback\<boolean>): void
1079
1080检查当前网络上的数据流量使用是否被计量,使用callback方式作为异步方法。
1081
1082**需要权限**:ohos.permission.GET_NETWORK_INFO
1083
1084**系统能力**:SystemCapability.Communication.NetManager.Core
1085
1086**参数:**
1087
1088| 参数名   | 类型                    | 必填 | 说明                                   |
1089| -------- | ----------------------- | ---- | -------------------------------------- |
1090| callback | AsyncCallback\<boolean> | 是   | 回调函数。当前网络上的数据流量使用被计量返回true。 |
1091
1092**错误码:**
1093
1094以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1095
1096| 错误码ID | 错误信息                        |
1097| ------- | -----------------------------  |
1098| 201     | Permission denied.             |
1099| 401     | Parameter error.                 |
1100| 2100002 | Failed to connect to the service.|
1101| 2100003 | System internal error.         |
1102
1103**示例:**
1104
1105```ts
1106import { connection } from '@kit.NetworkKit';
1107import { BusinessError } from '@kit.BasicServicesKit';
1108
1109connection.isDefaultNetMetered((error: BusinessError, data: boolean) => {
1110  console.log(JSON.stringify(error));
1111  console.log('data: ' + data);
1112});
1113```
1114
1115## connection.isDefaultNetMetered<sup>9+</sup>
1116
1117isDefaultNetMetered(): Promise\<boolean>
1118
1119检查当前网络上的数据流量使用是否被计量,使用Promise方式作为异步方法。
1120
1121**需要权限**:ohos.permission.GET_NETWORK_INFO
1122
1123**系统能力**:SystemCapability.Communication.NetManager.Core
1124
1125**返回值:**
1126
1127| 类型              | 说明                                            |
1128| ----------------- | ----------------------------------------------- |
1129| Promise\<boolean> | 以Promise形式返回,当前网络上的数据流量使用被计量true。 |
1130
1131**错误码:**
1132
1133以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1134
1135| 错误码ID | 错误信息                         |
1136| ------- | -------------------------------- |
1137| 201     | Permission denied.               |
1138| 2100002 | Failed to connect to the service.|
1139| 2100003 | System internal error.           |
1140
1141**示例:**
1142
1143```ts
1144import { connection } from '@kit.NetworkKit';
1145
1146connection.isDefaultNetMetered().then((data: boolean) => {
1147  console.log('data: ' + data);
1148});
1149```
1150
1151## connection.isDefaultNetMeteredSync<sup>10+</sup>
1152
1153isDefaultNetMeteredSync(): boolean
1154
1155检查当前网络上的数据流量使用是否被计量,使用同步方式返回。
1156
1157**需要权限**:ohos.permission.GET_NETWORK_INFO
1158
1159**系统能力**:SystemCapability.Communication.NetManager.Core
1160
1161**返回值:**
1162
1163| 类型              | 说明                                            |
1164| ----------------- | ----------------------------------------------- |
1165| boolean | 当前网络上的数据流量使用被计量true。 |
1166
1167**错误码:**
1168
1169以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1170
1171| 错误码ID | 错误信息                         |
1172| ------- | -------------------------------- |
1173| 201     | Permission denied.               |
1174| 2100002 | Failed to connect to the service.|
1175| 2100003 | System internal error.           |
1176
1177**示例:**
1178
1179```ts
1180import { connection } from '@kit.NetworkKit';
1181
1182let isMetered = connection.isDefaultNetMeteredSync();
1183```
1184
1185## connection.hasDefaultNet
1186
1187hasDefaultNet(callback: AsyncCallback\<boolean>): void
1188
1189检查默认数据网络是否被激活,使用callback方式作为异步方法。如果有默认数据网络,可以使用[getDefaultNet](#connectiongetdefaultnet)去获取。
1190
1191**需要权限**:ohos.permission.GET_NETWORK_INFO
1192
1193**系统能力**:SystemCapability.Communication.NetManager.Core
1194
1195**参数:**
1196
1197| 参数名   | 类型                    | 必填 | 说明                                   |
1198| -------- | ----------------------- | ---- | -------------------------------------- |
1199| callback | AsyncCallback\<boolean> | 是   | 回调函数。默认数据网络被激活返回true。 |
1200
1201**错误码:**
1202
1203以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1204
1205| 错误码ID | 错误信息                          |
1206| ------- | --------------------------------- |
1207| 201     | Permission denied.                |
1208| 401     | Parameter error.                  |
1209| 2100002 | Failed to connect to the service. |
1210| 2100003 | System internal error.            |
1211
1212**示例:**
1213
1214```ts
1215import { connection } from '@kit.NetworkKit';
1216import { BusinessError } from '@kit.BasicServicesKit';
1217
1218connection.hasDefaultNet((error: BusinessError, data: boolean) => {
1219  console.log(JSON.stringify(error));
1220  console.log('data: ' + data);
1221});
1222```
1223
1224## connection.hasDefaultNet
1225
1226hasDefaultNet(): Promise\<boolean>
1227
1228检查默认数据网络是否被激活,使用Promise方式作为异步方法。如果有默认数据网络,可以使用[getDefaultNet](#connectiongetdefaultnet)去获取。
1229
1230**需要权限**:ohos.permission.GET_NETWORK_INFO
1231
1232**系统能力**:SystemCapability.Communication.NetManager.Core
1233
1234**返回值:**
1235
1236| 类型              | 说明                                            |
1237| ----------------- | ----------------------------------------------- |
1238| Promise\<boolean> | 以Promise形式返回,默认数据网络被激活返回true。 |
1239
1240**错误码:**
1241
1242以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1243
1244| 错误码ID | 错误信息                        |
1245| ------- | -----------------------------  |
1246| 201     | Permission denied.             |
1247| 2100002 | Failed to connect to the service. |
1248| 2100003 | System internal error.         |
1249
1250**示例:**
1251
1252```ts
1253import { connection } from '@kit.NetworkKit';
1254
1255connection.hasDefaultNet().then((data: boolean) => {
1256  console.log('data: ' + data);
1257});
1258```
1259
1260## connection.hasDefaultNetSync<sup>10+</sup>
1261
1262hasDefaultNetSync(): boolean
1263
1264检查默认数据网络是否被激活,使用同步方式返回接口,如果被激活则返回true。
1265
1266**需要权限**:ohos.permission.GET_NETWORK_INFO
1267
1268**系统能力**:SystemCapability.Communication.NetManager.Core
1269
1270**返回值:**
1271
1272| 类型              | 说明                                            |
1273| ----------------- | ----------------------------------------------- |
1274| boolean | 默认数据网络被激活返回true。 |
1275
1276**错误码:**
1277
1278以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1279
1280| 错误码ID | 错误信息                        |
1281| ------- | -----------------------------  |
1282| 201     | Permission denied.             |
1283| 2100002 | Failed to connect to the service.|
1284| 2100003 | System internal error.         |
1285
1286**示例:**
1287
1288```ts
1289import { connection } from '@kit.NetworkKit';
1290
1291let isDefaultNet = connection.hasDefaultNetSync();
1292```
1293
1294
1295## connection.reportNetConnected
1296
1297reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
1298
1299向网络管理报告网络处于可用状态,使用callback方式作为异步方法。
1300
1301**需要权限**:ohos.permission.GET_NETWORK_INFOohos.permission.INTERNET
1302
1303**系统能力**:SystemCapability.Communication.NetManager.Core
1304
1305**参数:**
1306
1307| 参数名 | 类型 | 必填 | 说明 |
1308| -------- | -------- | -------- | -------- |
1309| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |
1310| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向网络管理报告网络处于可用状态成功,error为undefined,否则为错误对象。 |
1311
1312**错误码:**
1313
1314以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1315
1316| 错误码ID | 错误信息                        |
1317| ------- | -----------------------------  |
1318| 201     | Permission denied.             |
1319| 401     | Parameter error.               |
1320| 2100001 | Invalid parameter value.                |
1321| 2100002 | Failed to connect to the service. |
1322| 2100003 | System internal error.         |
1323
1324**示例:**
1325
1326```ts
1327import { connection } from '@kit.NetworkKit';
1328import { BusinessError } from '@kit.BasicServicesKit';
1329
1330connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
1331  connection.reportNetConnected(netHandle, (error: BusinessError) => {
1332    console.log(JSON.stringify(error));
1333  });
1334});
1335```
1336
1337## connection.reportNetConnected
1338
1339reportNetConnected(netHandle: NetHandle): Promise\<void\>
1340
1341向网络管理报告网络处于可用状态,使用Promise方式作为异步方法。
1342
1343**需要权限**:ohos.permission.GET_NETWORK_INFOohos.permission.INTERNET
1344
1345**系统能力**:SystemCapability.Communication.NetManager.Core
1346
1347**参数:**
1348
1349| 参数名 | 类型 | 必填 | 说明 |
1350| -------- | -------- | -------- | -------- |
1351| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |
1352
1353**返回值:**
1354| 类型 | 说明 |
1355| -------- | -------- |
1356| Promise&lt;void&gt; | 无返回值的Promise对象。 |
1357
1358**错误码:**
1359
1360以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1361
1362| 错误码ID | 错误信息                          |
1363| ------- | --------------------------------- |
1364| 201     | Permission denied.                |
1365| 401     | Parameter error.                  |
1366| 2100001 | Invalid parameter value.          |
1367| 2100002 | Failed to connect to the service. |
1368| 2100003 | System internal error.            |
1369
1370**示例:**
1371
1372```ts
1373import { connection } from '@kit.NetworkKit';
1374
1375connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
1376  connection.reportNetConnected(netHandle).then(() => {
1377    console.log(`report success`);
1378  });
1379});
1380```
1381
1382## connection.reportNetDisconnected
1383
1384reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
1385
1386向网络管理报告网络处于不可用状态,使用callback方式作为异步方法。
1387
1388**需要权限**:ohos.permission.GET_NETWORK_INFOohos.permission.INTERNET
1389
1390**系统能力**:SystemCapability.Communication.NetManager.Core
1391
1392**参数:**
1393
1394| 参数名 | 类型 | 必填 | 说明 |
1395| -------- | -------- | -------- | -------- |
1396| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |
1397| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向网络管理报告网络处于不可用状态成功,error为undefined,否则为错误对象。 |
1398
1399**错误码:**
1400
1401以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1402
1403| 错误码ID | 错误信息                        |
1404| ------- | -----------------------------  |
1405| 201     | Permission denied.             |
1406| 401     | Parameter error.               |
1407| 2100001 | Invalid parameter value.                |
1408| 2100002 | Failed to connect to the service. |
1409| 2100003 | System internal error.         |
1410
1411**示例:**
1412
1413```ts
1414import { connection } from '@kit.NetworkKit';
1415
1416connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
1417  connection.reportNetDisconnected(netHandle).then( () => {
1418    console.log(`report success`);
1419  });
1420});
1421```
1422
1423## connection.reportNetDisconnected
1424
1425reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
1426
1427向网络管理报告网络处于不可用状态,使用Promise方式作为异步方法。
1428
1429**需要权限**:ohos.permission.GET_NETWORK_INFOohos.permission.INTERNET
1430
1431**系统能力**:SystemCapability.Communication.NetManager.Core
1432
1433**参数:**
1434
1435| 参数名 | 类型 | 必填 | 说明 |
1436| -------- | -------- | -------- | -------- |
1437| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |
1438
1439**返回值:**
1440| 类型 | 说明 |
1441| -------- | -------- |
1442| Promise&lt;void&gt; | 无返回值的Promise对象。 |
1443
1444**错误码:**
1445
1446以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1447
1448| 错误码ID | 错误信息                          |
1449| ------- | --------------------------------- |
1450| 201     | Permission denied.                |
1451| 401     | Parameter error.                  |
1452| 2100001 | Invalid parameter value.          |
1453| 2100002 | Failed to connect to the service. |
1454| 2100003 | System internal error.            |
1455
1456**示例:**
1457
1458```ts
1459import { connection } from '@kit.NetworkKit';
1460
1461connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
1462  connection.reportNetDisconnected(netHandle).then( () => {
1463    console.log(`report success`);
1464  });
1465});
1466```
1467
1468## connection.getAddressesByName
1469
1470getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void
1471
1472使用对应网络解析主机名以获取所有IP地址,使用callback方式作为异步方法。
1473
1474**需要权限**:ohos.permission.INTERNET
1475
1476**系统能力**:SystemCapability.Communication.NetManager.Core
1477
1478**参数:**
1479
1480| 参数名   | 类型                                              | 必填 | 说明                                                         |
1481| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
1482| host     | string                                            | 是   | 需要解析的主机名。                                           |
1483| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | 是   | 回调函数。当使用默认网络解析主机名成功获取所有IP地址,error为undefined,data为获取到的所有IP地址;否则为错误对象。 |
1484
1485**错误码:**
1486
1487以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1488
1489| 错误码ID | 错误信息                          |
1490| ------- | --------------------------------- |
1491| 201     | Permission denied.                |
1492| 401     | Parameter error.                  |
1493| 2100001 | Invalid parameter value.          |
1494| 2100002 | Failed to connect to the service. |
1495| 2100003 | System internal error.            |
1496
1497**示例:**
1498
1499```ts
1500import { connection } from '@kit.NetworkKit';
1501import { BusinessError } from '@kit.BasicServicesKit';
1502
1503connection.getAddressesByName("xxxx", (error: BusinessError, data: connection.NetAddress[]) => {
1504  if (error) {
1505    console.error(`Failed to get addresses. Code:${error.code}, message:${error.message}`);
1506    return;
1507  }
1508  console.info("Succeeded to get data: " + JSON.stringify(data));
1509});
1510```
1511
1512## connection.getAddressesByName
1513
1514getAddressesByName(host: string): Promise\<Array\<NetAddress\>\>
1515
1516使用对应网络解析主机名以获取所有IP地址,使用Promise方式作为异步方法。
1517
1518**需要权限**:ohos.permission.INTERNET
1519
1520**系统能力**:SystemCapability.Communication.NetManager.Core
1521
1522**参数:**
1523
1524| 参数名 | 类型   | 必填 | 说明               |
1525| ------ | ------ | ---- | ------------------ |
1526| host   | string | 是   | 需要解析的主机名。 |
1527
1528**返回值:**
1529
1530| 类型                                        | 说明                          |
1531| ------------------------------------------- | ----------------------------- |
1532| Promise\<Array\<[NetAddress](#netaddress)>> | 以Promise形式返回所有IP地址。 |
1533
1534**错误码:**
1535
1536以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1537
1538| 错误码ID | 错误信息                        |
1539| ------- | -----------------------------  |
1540| 201     | Permission denied.             |
1541| 401     | Parameter error.               |
1542| 2100001 | Invalid parameter value.                |
1543| 2100002 | Failed to connect to the service. |
1544| 2100003 | System internal error.         |
1545
1546**示例:**
1547
1548```ts
1549import { connection } from '@kit.NetworkKit';
1550
1551connection.getAddressesByName("xxxx").then((data: connection.NetAddress[]) => {
1552  console.info("Succeeded to get data: " + JSON.stringify(data));
1553});
1554```
1555
1556## connection.addCustomDnsRule<sup>11+</sup>
1557
1558addCustomDnsRule(host: string, ip: Array\<string\>, callback: AsyncCallback\<void\>): void
1559
1560为当前应用程序添加自定义host和对应的IP地址的映射,使用callback方式作为异步方法。
1561
1562**需要权限**:ohos.permission.INTERNET
1563
1564**系统能力**:SystemCapability.Communication.NetManager.Core
1565
1566**参数:**
1567
1568| 参数名   | 类型                 | 必填 | 说明                                                         |
1569| -------- | -------------------- | ---- | ------------------------------------------------------------ |
1570| host     | string               | 是   | 需要自定义解析的主机名。                                     |
1571| ip       | Array\<string>       | 是   | 主机名所映射的IP地址列表。                                   |
1572| callback | AsyncCallback\<void> | 是   | 回调函数。当为当前应用程序添加自定义host和对应的ip地址的映射成功,error为undefined,否则为错误对象。 |
1573
1574**错误码:**
1575
1576以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1577
1578| 错误码ID | 错误信息                          |
1579| ------- | --------------------------------- |
1580| 201     | Permission denied.                |
1581| 401     | Parameter error.                  |
1582| 2100001 | Invalid parameter value.          |
1583| 2100002 | Failed to connect to the service. |
1584| 2100003 | System internal error.            |
1585
1586**示例:**
1587
1588```ts
1589import { connection } from '@kit.NetworkKit';
1590import { BusinessError } from '@kit.BasicServicesKit';
1591
1592connection.addCustomDnsRule("xxxx", ["xx.xx.xx.xx","xx.xx.xx.xx"], (error: BusinessError, data: void) => {
1593  if (error) {
1594    console.error(`Failed to get add custom dns rule. Code:${error.code}, message:${error.message}`);
1595    return;
1596  }
1597  console.info("Succeeded to get data: " + JSON.stringify(data));
1598})
1599```
1600
1601## connection.addCustomDnsRule<sup>11+</sup>
1602
1603addCustomDnsRule(host: string, ip: Array\<string\>): Promise\<void\>
1604
1605为当前应用程序添加自定义host和对应的IP地址的映射,使用Promise方式作为异步方法。
1606
1607**需要权限**:ohos.permission.INTERNET
1608
1609**系统能力**:SystemCapability.Communication.NetManager.Core
1610
1611**参数:**
1612
1613| 参数名 | 类型           | 必填 | 说明                       |
1614| ------ | -------------- | ---- | -------------------------- |
1615| host   | string         | 是   | 需要自定义解析的主机名。   |
1616| ip     | Array\<string> | 是   | 主机名所映射的IP地址列表。 |
1617
1618**返回值:**
1619
1620| 类型                   | 说明                    |
1621| ---------------------- | ----------------------- |
1622| Promise\<Array\<void>> | 无返回值的Promise对象。 |
1623
1624**错误码:**
1625
1626以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1627
1628| 错误码ID | 错误信息                          |
1629| ------- | --------------------------------- |
1630| 201     | Permission denied.                |
1631| 401     | Parameter error.                  |
1632| 2100001 | Invalid parameter value.          |
1633| 2100002 | Failed to connect to the service. |
1634| 2100003 | System internal error.            |
1635
1636**示例:**
1637
1638```ts
1639import { connection } from '@kit.NetworkKit';
1640import { BusinessError } from '@kit.BasicServicesKit';
1641
1642connection.addCustomDnsRule("xxxx", ["xx.xx.xx.xx","xx.xx.xx.xx"]).then(() => {
1643    console.info("success");
1644}).catch((error: BusinessError) => {
1645    console.error(JSON.stringify(error));
1646})
1647```
1648
1649## connection.removeCustomDnsRule<sup>11+</sup>
1650
1651removeCustomDnsRule(host: string, callback: AsyncCallback\<void\>): void
1652
1653删除当前应用程序中对应host的自定义DNS规则,使用callback方式作为异步方法。
1654
1655**需要权限**:ohos.permission.INTERNET
1656
1657**系统能力**:SystemCapability.Communication.NetManager.Core
1658
1659**参数:**
1660
1661| 参数名   | 类型                 | 必填 | 说明                                                         |
1662| -------- | -------------------- | ---- | ------------------------------------------------------------ |
1663| host     | string               | 是   | 需要删除自定义DNS规则的主机名。                              |
1664| callback | AsyncCallback\<void> | 是   | 回调函数。当删除当前应用程序中对应host的自定义DNS规则成功,error为undefined,否则为错误对象。 |
1665
1666**错误码:**
1667
1668以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1669
1670| 错误码ID | 错误信息                        |
1671| ------- | -----------------------------  |
1672| 201     | Permission denied.             |
1673| 401     | Parameter error.               |
1674| 2100001 | Invalid parameter value.                |
1675| 2100002 | Failed to connect to the service. |
1676| 2100003 | System internal error.         |
1677
1678**示例:**
1679
1680```ts
1681import { connection } from '@kit.NetworkKit';
1682import { BusinessError } from '@kit.BasicServicesKit';
1683
1684connection.removeCustomDnsRule("xxxx", (error: BusinessError, data: void) => {
1685  if (error) {
1686    console.error(`Failed to remove custom dns rule. Code:${error.code}, message:${error.message}`);
1687    return;
1688  }
1689  console.info("Succeeded to get data: " + JSON.stringify(data));
1690})
1691```
1692
1693## connection.removeCustomDnsRule<sup>11+</sup>
1694
1695removeCustomDnsRule(host: string): Promise\<void\>
1696
1697删除当前应用程序中对应host的自定义DNS规则,使用Promise方式作为异步方法。
1698
1699**需要权限**:ohos.permission.INTERNET
1700
1701**系统能力**:SystemCapability.Communication.NetManager.Core
1702
1703**参数:**
1704
1705| 参数名 | 类型   | 必填 | 说明                            |
1706| ------ | ------ | ---- | ------------------------------- |
1707| host   | string | 是   | 需要删除自定义DNS规则的主机名。 |
1708
1709**返回值:**
1710
1711| 类型                   | 说明                    |
1712| ---------------------- | ----------------------- |
1713| Promise\<Array\<void>> | 无返回值的Promise对象。 |
1714
1715**错误码:**
1716
1717以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1718
1719| 错误码ID | 错误信息                          |
1720| ------- | --------------------------------- |
1721| 201     | Permission denied.                |
1722| 401     | Parameter error.                  |
1723| 2100001 | Invalid parameter value.          |
1724| 2100002 | Failed to connect to the service. |
1725| 2100003 | System internal error.            |
1726
1727**示例:**
1728
1729```ts
1730import { connection } from '@kit.NetworkKit';
1731import { BusinessError } from '@kit.BasicServicesKit';
1732
1733connection.removeCustomDnsRule("xxxx").then(() => {
1734    console.log("success");
1735}).catch((error: BusinessError) => {
1736    console.log(JSON.stringify(error));
1737})
1738```
1739
1740## connection.clearCustomDnsRules<sup>11+</sup>
1741
1742clearCustomDnsRules(callback: AsyncCallback\<void\>): void
1743
1744删除当前应用程序的所有的自定义DNS规则,使用callback方式作为异步方法。
1745
1746**需要权限**:ohos.permission.INTERNET
1747
1748**系统能力**:SystemCapability.Communication.NetManager.Core
1749
1750**参数:**
1751
1752| 参数名   | 类型                 | 必填 | 说明                                                         |
1753| -------- | -------------------- | ---- | ------------------------------------------------------------ |
1754| callback | AsyncCallback\<void> | 是   | 回调函数。当删除当前应用程序的所有的自定义DNS规则成功,error为undefined,否则为错误对象。 |
1755
1756**错误码:**
1757
1758以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1759
1760| 错误码ID| 错误信息                           |
1761| ------- | --------------------------------- |
1762| 201     | Permission denied.                |
1763| 401     | Parameter error.                  |
1764| 2100001 | Invalid parameter value.          |
1765| 2100002 | Failed to connect to the service. |
1766| 2100003 | System internal error.            |
1767
1768**示例:**
1769
1770```ts
1771import { connection } from '@kit.NetworkKit';
1772import { BusinessError } from '@kit.BasicServicesKit';
1773
1774connection.clearCustomDnsRules((error: BusinessError, data: void) => {
1775  if (error) {
1776    console.error(`Failed to clear custom dns rules. Code:${error.code}, message:${error.message}`);
1777    return;
1778  }
1779  console.info("Succeeded to get data: " + JSON.stringify(data));
1780})
1781```
1782
1783## connection.clearCustomDnsRules<sup>11+</sup>
1784
1785clearCustomDnsRules(): Promise\<void\>
1786
1787删除当前应用程序的所有的自定义DNS规则,使用Promise方式作为异步方法。
1788
1789**需要权限**:ohos.permission.INTERNET
1790
1791**系统能力**:SystemCapability.Communication.NetManager.Core
1792
1793**返回值:**
1794
1795| 类型                   | 说明                    |
1796| ---------------------- | ----------------------- |
1797| Promise\<void\>        | 无返回值的Promise对象。  |
1798
1799**错误码:**
1800
1801以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1802
1803| 错误码ID | 错误信息                          |
1804| ------- | --------------------------------- |
1805| 201     | Permission denied.                |
1806| 2100001 | Invalid parameter value.          |
1807| 2100002 | Failed to connect to the service. |
1808| 2100003 | System internal error.            |
1809
1810**示例:**
1811
1812```ts
1813import { connection } from '@kit.NetworkKit';
1814import { BusinessError } from '@kit.BasicServicesKit';
1815
1816connection.clearCustomDnsRules().then(() => {
1817    console.log("success");
1818}).catch((error: BusinessError) => {
1819    console.log(JSON.stringify(error));
1820})
1821```
1822
1823
1824## NetConnection
1825
1826网络连接的句柄。
1827
1828> **说明:**
1829> 设备从无网络到有网络会触发netAvailable事件、netCapabilitiesChange事件和netConnectionPropertiesChange事件;
1830> 设备从有网络到无网络状态会触发netLost事件;
1831> 设备从WiFi到蜂窝会触发netLost事件(WiFi丢失)之后触发 netAvailable事件(蜂窝可用);
1832
1833### register
1834
1835register(callback: AsyncCallback\<void>): void
1836
1837订阅指定网络状态变化的通知。
1838
1839**需要权限**:ohos.permission.GET_NETWORK_INFO
1840
1841**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1842
1843**系统能力**:SystemCapability.Communication.NetManager.Core
1844
1845**参数:**
1846
1847| 参数名   | 类型                 | 必填 | 说明                                                         |
1848| -------- | -------------------- | ---- | ------------------------------------------------------------ |
1849| callback | AsyncCallback\<void> | 是   | 回调函数。当订阅指定网络状态变化的通知成功,error为undefined,否则为错误对象。 |
1850
1851**错误码:**
1852
1853以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1854
1855| 错误码ID |                       错误信息                       |
1856| ------- | ---------------------------------------------------- |
1857| 201     | Permission denied.                                   |
1858| 401     | Parameter error.                                     |
1859| 2100002 | Failed to connect to the service.                    |
1860| 2100003 | System internal error.                               |
1861| 2101008 | The callback already exists.                         |
1862| 2101022 | The number of requests exceeded the maximum allowed. |
1863
1864**示例:**
1865
1866```ts
1867import { connection } from '@kit.NetworkKit';
1868import { BusinessError } from '@kit.BasicServicesKit';
1869
1870let netCon: connection.NetConnection = connection.createNetConnection();
1871netCon.register((error: BusinessError) => {
1872  console.log(JSON.stringify(error));
1873});
1874```
1875
1876### unregister
1877
1878unregister(callback: AsyncCallback\<void>): void
1879
1880取消订阅默认网络状态变化的通知。
1881
1882**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1883
1884**系统能力**:SystemCapability.Communication.NetManager.Core
1885
1886**参数:**
1887
1888| 参数名   | 类型                 | 必填 | 说明                                                         |
1889| -------- | -------------------- | ---- | ------------------------------------------------------------ |
1890| callback | AsyncCallback\<void> | 是   | 回调函数。当取消订阅指定网络状态变化的通知成功,error为undefined,否则为错误对象。 |
1891
1892**错误码:**
1893
1894以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
1895
1896| 错误码ID | 错误信息                          |
1897| ------- | --------------------------------- |
1898| 401     | Parameter error.                  |
1899| 2100002 | Failed to connect to the service. |
1900| 2100003 | System internal error.            |
1901| 2101007 | The callback does not exist.      |
1902
1903**示例:**
1904
1905```ts
1906import { connection } from '@kit.NetworkKit';
1907import { BusinessError } from '@kit.BasicServicesKit';
1908
1909let netCon: connection.NetConnection = connection.createNetConnection();
1910netCon.unregister((error: BusinessError) => {
1911  console.log(JSON.stringify(error));
1912});
1913```
1914
1915### on('netAvailable')
1916
1917on(type: 'netAvailable', callback: Callback\<NetHandle>): void
1918
1919订阅网络可用事件。此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
1920
1921**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1922
1923**系统能力**:SystemCapability.Communication.NetManager.Core
1924
1925**参数:**
1926
1927| 参数名   | 类型                               | 必填 | 说明                                                         |
1928| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
1929| type     | string                             | 是   | 订阅事件,固定为'netAvailable'。<br>netAvailable:数据网络可用事件。 |
1930| callback | Callback\<[NetHandle](#nethandle)> | 是   | 回调函数,返回数据网络句柄。|
1931
1932**示例:**
1933
1934```ts
1935import { connection } from '@kit.NetworkKit';
1936import { BusinessError } from '@kit.BasicServicesKit';
1937
1938// 创建NetConnection对象
1939let netCon: connection.NetConnection = connection.createNetConnection();
1940
1941// 先使用register接口注册订阅事件
1942netCon.register((error: BusinessError) => {
1943  console.log(JSON.stringify(error));
1944});
1945
1946// 订阅网络可用事件。调用register后,才能接收到此事件通知
1947netCon.on('netAvailable', (data: connection.NetHandle) => {
1948  console.info("Succeeded to get data: " + JSON.stringify(data));
1949});
1950
1951// 使用unregister接口取消订阅
1952netCon.unregister((error: BusinessError) => {
1953  console.log(JSON.stringify(error));
1954});
1955```
1956
1957### on('netBlockStatusChange')
1958
1959on(type: 'netBlockStatusChange', callback: Callback\<NetBlockStatusInfo>): void
1960
1961订阅网络阻塞状态事件。此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
1962
1963**系统能力**:SystemCapability.Communication.NetManager.Core
1964
1965**参数:**
1966
1967| 参数名   | 类型                                                         | 必填 | 说明                                                         |
1968| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
1969| type     | string                                                       | 是   | 订阅事件,固定为'netBlockStatusChange'。<br/>netBlockStatusChange:网络阻塞状态事件。 |
1970| callback | Callback<[NetBlockStatusInfo](#netblockstatusinfo11)>        | 是   | 回调函数,获取网络阻塞状态信息。|
1971
1972**示例:**
1973
1974```ts
1975import { connection } from '@kit.NetworkKit';
1976import { BusinessError } from '@kit.BasicServicesKit';
1977
1978// 创建NetConnection对象
1979let netCon: connection.NetConnection = connection.createNetConnection();
1980
1981// 先使用register接口注册订阅事件
1982netCon.register((error: BusinessError) => {
1983  console.log(JSON.stringify(error));
1984});
1985
1986// 订阅网络阻塞状态事件。调用register后,才能接收到此事件通知
1987netCon.on('netBlockStatusChange', (data: connection.NetBlockStatusInfo) => {
1988  console.info("Succeeded to get data: " + JSON.stringify(data));
1989});
1990
1991// 使用unregister接口取消订阅
1992netCon.unregister((error: BusinessError) => {
1993  console.log(JSON.stringify(error));
1994});
1995```
1996
1997### on('netCapabilitiesChange')
1998
1999on(type: 'netCapabilitiesChange', callback: Callback\<NetCapabilityInfo\>): void
2000
2001订阅网络能力变化事件。此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
2002
2003**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2004
2005**系统能力**:SystemCapability.Communication.NetManager.Core
2006
2007**参数:**
2008
2009| 参数名   | 类型                                                         | 必填 | 说明                                                         |
2010| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2011| type     | string                                                       | 是   | 订阅事件,固定为'netCapabilitiesChange'。<br/>netCapabilitiesChange:网络能力变化事件。 |
2012| callback | Callback<[NetCapabilityInfo](#netcapabilityinfo10)>          | 是   | 回调函数,返回数据网络句柄(netHandle)和网络的能力信息(netCap)。|
2013
2014**示例:**
2015
2016```ts
2017import { connection } from '@kit.NetworkKit';
2018import { BusinessError } from '@kit.BasicServicesKit';
2019
2020// 创建NetConnection对象
2021let netCon: connection.NetConnection = connection.createNetConnection();
2022
2023// 先使用register接口注册订阅事件
2024netCon.register((error: BusinessError) => {
2025  console.log(JSON.stringify(error));
2026});
2027
2028// 订阅网络能力变化事件。调用register后,才能接收到此事件通知
2029netCon.on('netCapabilitiesChange', (data: connection.NetCapabilityInfo) => {
2030  console.info("Succeeded to get data: " + JSON.stringify(data));
2031});
2032
2033// 使用unregister接口取消订阅
2034netCon.unregister((error: BusinessError) => {
2035  console.log(JSON.stringify(error));
2036});
2037```
2038
2039### on('netConnectionPropertiesChange')
2040
2041on(type: 'netConnectionPropertiesChange', callback: Callback\<NetConnectionPropertyInfo\>): void
2042
2043订阅网络连接信息变化事件。此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
2044
2045**系统能力**:SystemCapability.Communication.NetManager.Core
2046
2047**参数:**
2048
2049| 参数名   | 类型                                                         | 必填 | 说明                                                         |
2050| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2051| type     | string                                                       | 是   | 订阅事件,固定为'netConnectionPropertiesChange'。<br/>netConnectionPropertiesChange:网络连接信息变化事件。 |
2052| callback | Callback<[NetConnectionPropertyInfo](#netconnectionpropertyinfo11)> | 是   | 回调函数,获取网络连接属性信息。|
2053
2054**示例:**
2055
2056```ts
2057import { connection } from '@kit.NetworkKit';
2058import { BusinessError } from '@kit.BasicServicesKit';
2059
2060// 创建NetConnection对象
2061let netCon: connection.NetConnection = connection.createNetConnection();
2062
2063// 先使用register接口注册订阅事件
2064netCon.register((error: BusinessError) => {
2065  console.log(JSON.stringify(error));
2066});
2067
2068// 订阅网络连接信息变化事件。调用register后,才能接收到此事件通知
2069netCon.on('netConnectionPropertiesChange', (data: connection.NetConnectionPropertyInfo) => {
2070  console.info("Succeeded to get data: " + JSON.stringify(data));
2071});
2072
2073// 使用unregister接口取消订阅
2074netCon.unregister((error: BusinessError) => {
2075  console.log(JSON.stringify(error));
2076});
2077```
2078
2079### on('netLost')
2080
2081on(type: 'netLost', callback: Callback\<NetHandle>): void
2082
2083订阅网络丢失事件。此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
2084
2085**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2086
2087**系统能力**:SystemCapability.Communication.NetManager.Core
2088
2089**参数:**
2090
2091| 参数名   | 类型                               | 必填 | 说明                                                         |
2092| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
2093| type     | string                             | 是   | 订阅事件,固定为'netLost'。<br/>netLost:网络严重中断或正常断开事件。 |
2094| callback | Callback\<[NetHandle](#nethandle)> | 是   | 回调函数,数据网络句柄(netHandle)。|
2095
2096**示例:**
2097
2098```ts
2099import { connection } from '@kit.NetworkKit';
2100import { BusinessError } from '@kit.BasicServicesKit';
2101
2102// 创建NetConnection对象
2103let netCon: connection.NetConnection = connection.createNetConnection();
2104
2105// 先使用register接口注册订阅事件
2106netCon.register((error: BusinessError) => {
2107  console.log(JSON.stringify(error));
2108});
2109
2110// 订阅网络丢失事件。调用register后,才能接收到此事件通知
2111netCon.on('netLost', (data: connection.NetHandle) => {
2112  console.info("Succeeded to get data: " + JSON.stringify(data));
2113});
2114
2115// 使用unregister接口取消订阅
2116netCon.unregister((error: BusinessError) => {
2117  console.log(JSON.stringify(error));
2118});
2119```
2120
2121### on('netUnavailable')
2122
2123on(type: 'netUnavailable', callback: Callback\<void>): void
2124
2125订阅网络不可用事件。此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。
2126
2127**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2128
2129**系统能力**:SystemCapability.Communication.NetManager.Core
2130
2131**参数:**
2132
2133| 参数名   | 类型            | 必填 | 说明                                                         |
2134| -------- | --------------- | ---- | ------------------------------------------------------------ |
2135| type     | string          | 是   | 订阅事件,固定为'netUnavailable'。<br/>netUnavailable:网络不可用事件。 |
2136| callback | Callback\<void> | 是   | 回调函数,无返回结果。|
2137
2138**示例:**
2139
2140```ts
2141import { connection } from '@kit.NetworkKit';
2142import { BusinessError } from '@kit.BasicServicesKit';
2143
2144// 创建NetConnection对象
2145let netCon: connection.NetConnection = connection.createNetConnection();
2146
2147// 先使用register接口注册订阅事件
2148netCon.register((error: BusinessError) => {
2149  console.log(JSON.stringify(error));
2150});
2151
2152// 订阅网络不可用事件。调用register后,才能接收到此事件通知
2153netCon.on('netUnavailable', () => {
2154  console.info("Succeeded to get unavailable net event");
2155});
2156
2157// 使用unregister接口取消订阅
2158netCon.unregister((error: BusinessError) => {
2159  console.log(JSON.stringify(error));
2160});
2161```
2162
2163## NetHandle
2164
2165数据网络的句柄。
2166
2167在调用NetHandle的方法之前,需要先获取NetHandle对象。
2168
2169**系统能力**:SystemCapability.Communication.NetManager.Core
2170
2171### 属性
2172
2173| 名称    | 类型   | 必填 | 说明                      |
2174| ------ | ------ | --- |------------------------- |
2175| netId  | number | 是  |  网络ID,取值为0代表没有默认网络,其余取值必须大于等于100。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2176
2177### bindSocket<sup>9+</sup>
2178
2179bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void
2180
2181将TCPSocket或UDPSocket绑定到当前网络,使用callback方式作为异步方法。
2182
2183**系统能力**:SystemCapability.Communication.NetManager.Core
2184
2185**参数:**
2186
2187| 参数名      | 类型                     | 必填 | 说明                            |
2188| ----------- | ------------------------ | ---- | -------------------------------|
2189| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | 是 | 待绑定的TCPSocket或UDPSocket对象。|
2190| callback    | AsyncCallback\<void>      | 是   | 回调函数。当TCPSocket或UDPSocket成功绑定到当前网络,error为undefined,否则为错误对象。 |
2191
2192**错误码:**
2193
2194以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
2195
2196| 错误码ID | 错误信息                          |
2197| ------- | --------------------------------- |
2198| 401     | Parameter error.                  |
2199| 2100001 | Invalid parameter value.          |
2200| 2100002 | Failed to connect to the service. |
2201| 2100003 | System internal error.            |
2202
2203**示例:**
2204
2205```ts
2206import { connection, socket } from '@kit.NetworkKit';
2207import { BusinessError } from '@kit.BasicServicesKit';
2208
2209interface Data {
2210  message: ArrayBuffer,
2211  remoteInfo: socket.SocketRemoteInfo
2212}
2213
2214  connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
2215  if (netHandle.netId == 0) {
2216    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常情况,需要额外处理
2217  }
2218  let tcp : socket.TCPSocket = socket.constructTCPSocketInstance();
2219  let udp : socket.UDPSocket = socket.constructUDPSocketInstance();
2220  let socketType = "TCPSocket";
2221  if (socketType == "TCPSocket") {
2222    tcp.bind({address:"192.168.xxx.xxx",
2223              port:8080,
2224              family:1} as socket.NetAddress, (error: Error) => {
2225      if (error) {
2226        console.log('bind fail');
2227        return;
2228      }
2229      netHandle.bindSocket(tcp, (error: BusinessError, data: void) => {
2230        if (error) {
2231          console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`);
2232          return;
2233        } else {
2234          console.info(JSON.stringify(data));
2235        }
2236      });
2237    });
2238  } else {
2239    let callback: (value: Data) => void = (value: Data) => {
2240      console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
2241    };
2242    udp.bind({address:"192.168.xxx.xxx",
2243              port:8080,
2244              family:1} as socket.NetAddress, (error: BusinessError) => {
2245      if (error) {
2246        console.error(`Failed to bind. Code:${error.code}, message:${error.message}`);
2247        return;
2248      }
2249      udp.on('message', (data: Data) => {
2250        console.info("Succeeded to get data: " + JSON.stringify(data));
2251      });
2252      netHandle.bindSocket(udp, (error: BusinessError, data: void) => {
2253        if (error) {
2254          console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`);
2255          return;
2256        } else {
2257          console.info(JSON.stringify(data));
2258        }
2259      });
2260    });
2261  }
2262})
2263```
2264
2265### bindSocket<sup>9+</sup>
2266
2267bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void\>
2268
2269将TCPSocket或UDPSockett绑定到当前网络,使用Promise方式作为异步方法。
2270
2271**系统能力**:SystemCapability.Communication.NetManager.Core
2272
2273**参数:**
2274
2275| 参数名          | 类型                  | 必填  | 说明                           |
2276| --------------- | --------------------- | ---- | ------------------------------ |
2277| socketParam     | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | 是   | 待绑定的TCPSocket或UDPSocket对象。|
2278
2279**返回值:**
2280
2281| 类型           | 说明                   |
2282| -------------- | ---------------------- |
2283| Promise\<void> | 无返回值的Promise对象。 |
2284
2285**错误码:**
2286
2287以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
2288
2289| 错误码ID | 错误信息                          |
2290| ------- | --------------------------------- |
2291| 401     | Parameter error.                  |
2292| 2100001 | Invalid parameter value.          |
2293| 2100002 | Failed to connect to the service. |
2294| 2100003 | System internal error.            |
2295
2296**示例:**
2297
2298```ts
2299import { connection, socket } from '@kit.NetworkKit';
2300import { BusinessError } from '@kit.BasicServicesKit';
2301
2302interface Data {
2303  message: ArrayBuffer,
2304  remoteInfo: socket.SocketRemoteInfo
2305}
2306
2307connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
2308  if (netHandle.netId == 0) {
2309    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
2310    return;
2311  }
2312  let tcp : socket.TCPSocket = socket.constructTCPSocketInstance();
2313  let udp : socket.UDPSocket = socket.constructUDPSocketInstance();
2314  let socketType = "TCPSocket";
2315  if (socketType == "TCPSocket") {
2316    tcp.bind({address:"192.168.xxx.xxx",
2317              port:8080,
2318              family:1} as socket.NetAddress, (error: Error) => {
2319      if (error) {
2320        console.log('bind fail');
2321        return;
2322      }
2323      netHandle.bindSocket(tcp).then(() => {
2324        console.info("bind socket success");
2325      }).catch((error: BusinessError) => {
2326        console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`);
2327      });
2328    });
2329  } else {
2330    let callback: (value: Data) => void = (value: Data) => {
2331      console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
2332    }
2333    udp.bind({address:"192.168.xxx.xxx",
2334              port:8080,
2335              family:1} as socket.NetAddress, (error: BusinessError) => {
2336      if (error) {
2337        console.error(`Failed to bind. Code:${error.code}, message:${error.message}`);
2338        return;
2339      }
2340      udp.on('message', (data: Data) => {
2341        console.info("Succeeded to get data: " + JSON.stringify(data));
2342      });
2343      netHandle.bindSocket(udp).then(() => {
2344        console.info("bind socket success");
2345      }).catch((error: BusinessError) => {
2346        console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`);
2347      });
2348    });
2349  }
2350});
2351```
2352
2353### getAddressesByName
2354
2355getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>\>\): void
2356
2357使用对应网络解析主机名以获取所有IP地址,使用callback方式作为异步方法。
2358
2359**需要权限**:ohos.permission.INTERNET
2360
2361**系统能力**:SystemCapability.Communication.NetManager.Core
2362
2363**参数:**
2364
2365| 参数名   | 类型                                              | 必填 | 说明                                                         |
2366| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
2367| host     | string                                            | 是   | 需要解析的主机名。                                           |
2368| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | 是   | 回调函数。当使用对应网络解析主机名成功获取所有IP地址,error为undefined,data为获取到的所有IP地址;否则为错误对象。 |
2369
2370**错误码:**
2371
2372以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
2373
2374| 错误码ID | 错误信息                          |
2375| ------- | --------------------------------- |
2376| 201     | Permission denied.                |
2377| 401     | Parameter error.                  |
2378| 2100001 | Invalid parameter value.          |
2379| 2100002 | Failed to connect to the service. |
2380| 2100003 | System internal error.            |
2381
2382**示例:**
2383
2384```ts
2385import { connection } from '@kit.NetworkKit';
2386import { BusinessError } from '@kit.BasicServicesKit';
2387
2388connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
2389  if (netHandle.netId == 0) {
2390    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
2391    return;
2392  }
2393  let host = "xxxx";
2394  netHandle.getAddressesByName(host, (error: BusinessError, data: connection.NetAddress[]) => {
2395    if (error) {
2396      console.error(`Failed to get addresses. Code:${error.code}, message:${error.message}`);
2397      return;
2398    }
2399    console.info("Succeeded to get data: " + JSON.stringify(data));
2400  });
2401});
2402```
2403
2404### getAddressesByName
2405
2406getAddressesByName(host: string): Promise\<Array\<NetAddress>>
2407
2408使用对应网络解析主机名以获取所有IP地址,使用Promise方式作为异步方法。
2409
2410**需要权限**:ohos.permission.INTERNET
2411
2412**系统能力**:SystemCapability.Communication.NetManager.Core
2413
2414**参数:**
2415
2416| 参数名 | 类型   | 必填 | 说明               |
2417| ------ | ------ | ---- | ------------------ |
2418| host   | string | 是   | 需要解析的主机名。 |
2419
2420**返回值:**
2421
2422| 类型                                        | 说明                          |
2423| ------------------------------------------- | ----------------------------- |
2424| Promise\<Array\<[NetAddress](#netaddress)>> | 以Promise形式返回所有IP地址。 |
2425
2426**错误码:**
2427
2428以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
2429
2430| 错误码ID | 错误信息                          |
2431| ------- | --------------------------------- |
2432| 201     | Permission denied.                |
2433| 401     | Parameter error.                  |
2434| 2100001 | Invalid parameter value.          |
2435| 2100002 | Failed to connect to the service. |
2436| 2100003 | System internal error.            |
2437
2438**示例:**
2439
2440```ts
2441import { connection } from '@kit.NetworkKit';
2442
2443connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
2444  if (netHandle.netId == 0) {
2445    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
2446    return;
2447  }
2448  let host = "xxxx";
2449  netHandle.getAddressesByName(host).then((data: connection.NetAddress[]) => {
2450    console.info("Succeeded to get data: " + JSON.stringify(data));
2451  });
2452});
2453```
2454
2455### getAddressByName
2456
2457getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void
2458
2459使用对应网络解析主机名以获取第一个IP地址,使用callback方式作为异步方法。
2460
2461**需要权限**:ohos.permission.INTERNET
2462
2463**系统能力**:SystemCapability.Communication.NetManager.Core
2464
2465**参数:**
2466
2467| 参数名   | 类型                                      | 必填 | 说明                                                         |
2468| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
2469| host     | string                                    | 是   | 需要解析的主机名。                                           |
2470| callback | AsyncCallback\<[NetAddress](#netaddress)> | 是   | 回调函数。当使用对应网络解析主机名获取第一个IP地址成功,error为undefined,data为获取的第一个IP地址;否则为错误对象。 |
2471
2472**错误码:**
2473
2474以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
2475
2476| 错误码ID | 错误信息                          |
2477| ------- | --------------------------------- |
2478| 201     | Permission denied.                |
2479| 401     | Parameter error.                  |
2480| 2100001 | Invalid parameter value.          |
2481| 2100002 | Failed to connect to the service. |
2482| 2100003 | System internal error.            |
2483
2484**示例:**
2485
2486```ts
2487import { connection } from '@kit.NetworkKit';
2488import { BusinessError } from '@kit.BasicServicesKit';
2489
2490connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
2491  if (netHandle.netId == 0) {
2492    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
2493    return;
2494  }
2495  let host = "xxxx";
2496  netHandle.getAddressByName(host, (error: BusinessError, data: connection.NetAddress) => {
2497    if (error) {
2498      console.error(`Failed to get address. Code:${error.code}, message:${error.message}`);
2499      return;
2500    }
2501    console.info("Succeeded to get data: " + JSON.stringify(data));
2502  });
2503});
2504```
2505
2506### getAddressByName
2507
2508getAddressByName(host: string): Promise\<NetAddress>
2509
2510使用对应网络解析主机名以获取第一个IP地址,使用Promise方式作为异步方法。
2511
2512**需要权限**:ohos.permission.INTERNET
2513
2514**系统能力**:SystemCapability.Communication.NetManager.Core
2515
2516**参数:**
2517
2518| 参数名 | 类型   | 必填 | 说明               |
2519| ------ | ------ | ---- | ------------------ |
2520| host   | string | 是   | 需要解析的主机名。 |
2521
2522**返回值:**
2523
2524| 类型                                | 说明                            |
2525| ----------------------------------- | ------------------------------- |
2526| Promise\<[NetAddress](#netaddress)> | 以Promise形式返回第一个IP地址。 |
2527
2528**错误码:**
2529
2530以下错误码的详细介绍请参见[网络连接管理错误码](errorcode-net-connection.md)。
2531
2532| 错误码ID | 错误信息                          |
2533| ------- | --------------------------------- |
2534| 201     | Permission denied.                |
2535| 401     | Parameter error.                  |
2536| 2100001 | Invalid parameter value.          |
2537| 2100002 | Failed to connect to the service. |
2538| 2100003 | System internal error.            |
2539
2540**示例:**
2541
2542```ts
2543import { connection } from '@kit.NetworkKit';
2544
2545connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
2546  if (netHandle.netId == 0) {
2547    // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
2548    return;
2549  }
2550  let host = "xxxx";
2551  netHandle.getAddressByName(host).then((data: connection.NetAddress) => {
2552    console.info("Succeeded to get data: " + JSON.stringify(data));
2553  });
2554});
2555```
2556
2557## NetCap
2558
2559网络具体能力。
2560
2561**系统能力**:SystemCapability.Communication.NetManager.Core
2562
2563| 名称                  | 值   | 说明                   |
2564| ------------------------ | ---- | ---------------------- |
2565| NET_CAPABILITY_MMS | 0 | 表示网络可以访问运营商的MMSC(Multimedia&nbsp;Message&nbsp;Service,多媒体短信服务)发送和接收彩信。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2566| NET_CAPABILITY_NOT_METERED | 11 | 表示网络流量未被计费。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2567| NET_CAPABILITY_INTERNET  | 12   | 表示该网络应具有访问Internet的能力,该能力由网络提供者设置,但该网络访问Internet的连通性并未被网络管理成功验证。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2568| NET_CAPABILITY_NOT_VPN | 15 | 表示网络不使用VPN(Virtual&nbsp;Private&nbsp;Network,虚拟专用网络)。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2569| NET_CAPABILITY_VALIDATED | 16   | 表示网络管理通过该网络与华为云地址成功建立连接,该能力由网络管理模块设置。<br>请注意,网络管理可能会与华为云地址建立连接失败,导致网络能力不具备此标记位,但不完全代表该网络无法访问互联网。另外,对于新完成连接的网络,由于网络正在进行连通性验证,此值可能无法反映真实的验证结果。对此,您可以通过NET_CAPABILITY_CHECKING_CONNECTIVITY<sup>12+</sup>检查网络是否正在检测连通性。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2570| NET_CAPABILITY_PORTAL<sup>12+</sup> | 17   | 表示系统发现该网络存在强制网络门户,需要用户登陆认证,该能力由网络管理模块设置。<br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
2571| NET_CAPABILITY_CHECKING_CONNECTIVITY<sup>12+</sup> | 31   | 表示网络管理正在检验当前网络的连通性,此值会在网络连接时设置,直到连通性检测结束后不再设置,当此值存在时,NET_CAPABILITY_VALIDATED的值可能不准确。<br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
2572
2573## NetBearType
2574
2575网络类型。
2576
2577**系统能力**:SystemCapability.Communication.NetManager.Core
2578
2579|            名称         | 值   | 说明        |
2580| ----------------------- | ---- | ---------- |
2581| BEARER_CELLULAR | 0    | 蜂窝网络。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。  |
2582| BEARER_WIFI     | 1    | Wi-Fi网络。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2583| BEARER_BLUETOOTH<sup>12+</sup> | 2    | 蓝牙网络。<br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
2584| BEARER_ETHERNET | 3    | 以太网网络。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2585| BEARER_VPN<sup>12+</sup>| 4    | VPN网络。   |
2586
2587## HttpProxy<sup>10+</sup>
2588
2589网络代理配置信息
2590
2591**系统能力**:SystemCapability.Communication.NetManager.Core
2592
2593| 名称    | 类型   | 必填 | 说明                      |
2594| ------ | ------ | --- |------------------------- |
2595| host  | string | 是  |  代理服务器主机名。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。|
2596| port  | number | 是  |  主机端口。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2597| exclusionList  | Array\<string\> | 是  | 不使用代理的主机名列表,主机名支持域名、IP地址以及通配符形式,详细匹配规则如下:<br/>1、域名匹配规则:<br/>(1)完全匹配:代理服务器主机名只要与列表中的任意一个主机名完全相同,就可以匹配。<br/>(2)包含匹配:代理服务器主机名只要包含列表中的任意一个主机名,就可以匹配。<br/>例如,如果在主机名列表中设置了 “ample.com”,则  “ample.com”、“www.ample.com”、“ample.com:80”都会被匹配,而 “www.example.com”、“ample.com.org”则不会被匹配。<br/>2、IP地址匹配规则:代理服务器主机名只要与列表中的任意一个IP地址完全相同,就可以匹配。<br/>3、域名跟IP地址可以同时添加到列表中进行匹配。<br/>4、单个“\*”是唯一有效的通配符,当列表中只有通配符时,将与所有代理服务器主机名匹配,表示禁用代理。通配符只能单独添加,不可以与其他域名、IP地址一起添加到列表中,否则通配符将不生效。<br/>5、匹配规则不区分主机名大小写。<br/>6、匹配主机名时,不考虑http和https等协议前缀。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2598| username<sup>12+</sup>  | string | 否 |  使用代理的用户名。|
2599| password<sup>12+</sup>  | string | 否 |  使用代理的用户密码。|
2600
2601## NetSpecifier
2602
2603提供承载数据网络能力的实例。
2604
2605**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2606
2607**系统能力**:SystemCapability.Communication.NetManager.Core
2608
2609| 名称                     | 类型                                | 必填  | 说明                                                         |
2610| ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
2611| netCapabilities         | [NetCapabilities](#netcapabilities) |  是  | 存储数据网络的传输能力和承载类型。                                |
2612| bearerPrivateIdentifier | string                              |  否  |  网络标识符,蜂窝网络的标识符是"slot0"(对应SIM卡1)、"slot1"(对应SIM卡2)。从API12开始可以通过传递注册的WLAN热点信息表示应用希望激活的指定的WLAN网络。 |
2613
2614**示例:**
2615
2616```ts
2617import { connection } from '@kit.NetworkKit';
2618import { wifiManager } from '@kit.ConnectivityKit';
2619import { BusinessError } from '@kit.BasicServicesKit';
2620
2621let config: wifiManager.WifiDeviceConfig = {
2622  ssid: "TEST",
2623  preSharedKey: "**********",
2624  securityType: wifiManager.WifiSecurityType.WIFI_SEC_TYPE_PSK
2625};
2626// 通过wifiManager.addCandidateConfig获取注册WLAN的networkId
2627let networkId: number = await wifiManager.addCandidateConfig(config);
2628let netConnectionWlan = connection.createNetConnection({
2629  netCapabilities: {
2630    bearerTypes: [connection.NetBearType.BEARER_WIFI]
2631  },
2632  bearerPrivateIdentifier: `${networkId}`
2633});
2634netConnectionWlan.register((error: BusinessError) => {
2635  console.log(JSON.stringify(error));
2636});
2637```
2638
2639## NetCapabilityInfo<sup>10+</sup>
2640
2641提供承载数据网络能力的实例。
2642
2643**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2644
2645**系统能力**:SystemCapability.Communication.NetManager.Core
2646
2647| 名称                    | 类型                                 | 必填  | 说明                                                         |
2648| ----------------------- | ------------------------------------ | ---- | ------------------------------------------------------------ |
2649| netHandle               | [NetHandle](#nethandle)              |  是  | 数据网络句柄。                                                |
2650| netCap                  |  [NetCapabilities](#netcapabilities) |  是  |  存储数据网络的传输能力和承载类型。                            |
2651
2652## NetCapabilities
2653
2654网络的能力集。
2655
2656**系统能力**:SystemCapability.Communication.NetManager.Core
2657
2658| 名称                  | 类型                                | 必填 | 说明                     |
2659| --------------------- | ---------------------------------- | --- | ------------------------ |
2660| linkUpBandwidthKbps   | number                             |  否 |  上行(设备到网络)带宽,单位(kb/s),0表示无法评估当前网络带宽。|
2661| linkDownBandwidthKbps | number                             |  否 |  下行(网络到设备)带宽,单位(kb/s),0表示无法评估当前网络带宽。|
2662| networkCap            | Array\<[NetCap](#netcap)>           |  否 |  网络具体能力。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。           |
2663| bearerTypes           | Array\<[NetBearType](#netbeartype)> |  是 |  网络类型。数组里面只包含了一种具体的网络类型。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。      |
2664
2665## NetConnectionPropertyInfo<sup>11+</sup>
2666
2667网络连接信息
2668
2669**系统能力**:SystemCapability.Communication.NetManager.Core
2670
2671### 属性
2672
2673| 名称                 |                          类型                        | 必填 |         说明           |
2674| -------------------- | --------------------------------------------------- | ---- |----------------------- |
2675| netHandle            | [NetHandle](#nethandle)                             | 是   |数据网络句柄(netHandle)。|
2676| connectionProperties | [ConnectionProperties](#connectionproperties)       | 是   |网络连接属性。           |
2677
2678## NetBlockStatusInfo<sup>11+</sup>
2679
2680获取网络状态信息。
2681
2682**系统能力**:SystemCapability.Communication.NetManager.Core
2683
2684### 属性
2685
2686| 名称                 | 类型                                  | 必填 |            说明            |
2687| -------------------- | ------------------------------------- | --- |--------------------------- |
2688| netHandle            | [NetHandle](#nethandle)               | 是   |数据网络句柄(netHandle)。   |
2689| blocked              | boolean                               | 是   |标识当前网络是否是堵塞状态。 |
2690
2691## ConnectionProperties
2692
2693网络连接信息。
2694
2695**系统能力**:SystemCapability.Communication.NetManager.Core
2696
2697| 名称          |                类型                 | 必填 |               说明                     |
2698| ------------- | ----------------------------------- | ----|--------------------------------------- |
2699| interfaceName | string                              | 是 |网卡名称。                                |
2700| domains       | string                              | 是 |域名。                                    |
2701| linkAddresses | Array\<[LinkAddress](#linkaddress)> | 是 |链路信息。                                |
2702| routes        | Array\<[RouteInfo](#routeinfo)>     | 是 |路由信息。                                |
2703| dnses         | Array\<[NetAddress](#netaddress)>   | 是 |网络地址,参考[NetAddress](#netaddress)。 |
2704| mtu           | number                              | 是 |最大传输单元。                            |
2705
2706## RouteInfo
2707
2708网络路由信息。
2709
2710**系统能力**:SystemCapability.Communication.NetManager.Core
2711
2712| 名称           | 类型                        | 必填 |     说明      |
2713| -------------- | --------------------------- | --- |-------------- |
2714| interface      | string                      | 是 |网卡名称。       |
2715| destination    | [LinkAddress](#linkaddress) | 是 |目的地址。       |
2716| gateway        | [NetAddress](#netaddress)   | 是 |网关地址。       |
2717| hasGateway     | boolean                     | 是 |是否有网关。     |
2718| isDefaultRoute | boolean                     | 是 |是否为默认路由。 |
2719
2720## LinkAddress
2721
2722网络链路信息。
2723
2724**系统能力**:SystemCapability.Communication.NetManager.Core
2725
2726| 名称         |           类型            | 必填 |        说明         |
2727| ------------ | ------------------------- |---- |-------------------- |
2728| address      | [NetAddress](#netaddress) | 是  | 链路地址。           |
2729| prefixLength | number                    | 是  |链路地址前缀的长度。  |
2730
2731## NetAddress
2732
2733网络地址。
2734
2735**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2736
2737**系统能力**:SystemCapability.Communication.NetManager.Core
2738
2739|  名称   | 类型   |必填|            说明              |
2740| ------- | ------ | -- |---------------------------- |
2741| address | string | 是 |地址。                       |
2742| family  | number | 否 |IPv4 = 1,IPv6 = 2,默认IPv4。|
2743| port    | number | 否 |端口,取值范围\[0, 65535]。   |
2744
2745## HttpRequest
2746
2747type HttpRequest = http.HttpRequest
2748
2749获取一个HTTP请求。
2750
2751**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2752
2753**系统能力**:SystemCapability.Communication.NetStack
2754
2755|       类型       |            说明             |
2756| ---------------- | --------------------------- |
2757| http.HttpRequest | 定义HTTP请求任务。在调用HttpRequest提供的API之前。 |
2758
2759## TCPSocket
2760
2761type TCPSocket = socket.TCPSocket
2762
2763获取一个TCPSocket对象。
2764
2765**原子化服务API:** 从API version 10开始,该接口支持在原子化服务中使用。
2766
2767**系统能力**:SystemCapability.Communication.NetStack
2768
2769|       类型       |            说明             |
2770| ---------------- | --------------------------- |
2771| socket.TCPSocket | 定义一个TCPSocket连接。     |
2772
2773## UDPSocket
2774
2775type UDPSocket = socket.UDPSocket
2776
2777获取一个UDPSocket对象。
2778
2779**原子化服务API:** 从API version 10开始,该接口支持在原子化服务中使用。
2780
2781**系统能力**:SystemCapability.Communication.NetStack
2782
2783|       类型       |            说明             |
2784| ---------------- | --------------------------- |
2785| socket.UDPSocket | 定义UDPSocket连接。     |
2786