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