• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Network Management
2
3
4## Introduction
5
6As a mandatory component for device networking, the network management subsystem implements unified connection management, traffic management, policy management, network sharing of different types of networks, and provides network protocol stack capabilities. An application can call APIs to obtain connection information of a data network, query and subscribe to connection status, network traffic data, and network policy, share the network, and transfer data using a network protocol stack.
7
8The figure below shows the architecture of the network management subsystem. The network management subsystem consists of the following components:
9
10-   Basic network management: provides basic network connection management and related JS and native APIs, including connection priority management, connection information query, connection status observation, DNS resolution, traffic management, networking policy management, and physical network management.
11-   Extended network management: provides extended network management capabilities and related JS and native APIs, including Ethernet connection and hotspot sharing.
12-   Network protocol stacks: provides basic network protocol stacks (such as HTTP, HTTPS, WebSocket, and TCP/UDP/TLS socket) and related JS APIs.
13
14**Figure 1** Architecture of the network management subsystem
15
16![](figures/en_architecture-of-netmanager-subsystem.png)
17
18## Directory Structure
19
20```
21foundation/communication/
22├── netmanager_base            # Basic network management
23├── netmanager_ext             # Extended network management
24└── netstack                   # Network protocol stacks
25```
26
27## Usage
28
29### Observing Network Status Changes
30
311. Import the connection namespace from **@ohos.net.connection.d.ts**.
32
332. Call **createNetConnection()** to create a **NetConnection** object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used.
34
353. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**.
36
374. Call **conn.register()** to subscribe to network status changes of the specified network.
38
395. When the network is available, the callback will be invoked to return the **netAvailable** event.
40
416. Call **conn.unregister()** to unsubscribe from the network status changes if required.
42
43   ```
44   // Import the connection namespace.
45   import connection from '@ohos.net.connection'
46
47   let netCap = {
48       // Set the network type to CELLULAR.
49       bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
50       // Set the network capability to INTERNET.
51       networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET],
52   };
53   let netSpec = {
54       netCapabilities: netCap,
55   };
56   // Set the timeout interval to 10s.
57   let timeout = 10 * 1000;
58   // Create a NetConnection object.
59   let conn = connection.createNetConnection(netSpec, timeout);
60   // Subscribe to the netAvailable event.
61   conn.on('netAvailable', (data=> {
62       console.log("net is available, netId is " + data.netId);
63   }));
64   // Register an observer for network status changes.
65   conn.register((err, data) => {});
66   // Unregister the observer for network status changes.
67   conn.unregister((err, data) => {});
68   ```
69
70### Sharing a Network
71
721. Import the **sharing** namespace from **@ohos.net.sharing**.
732. Set the network sharing type.
743. Start network sharing.
754. Stop network sharing.
76```
77// Import the connection namespace.
78import sharing from '@ohos.net.sharing';
79// Set the network sharing type.
80this.sharingType = 0;   // The value 0 indicates Wi-Fi, 1 indicates USB, and 2 indicates Bluetooth.
81// Start network sharing.
82sharing.startSharing(this.sharingType,(err)=>{
83    this.callBack(err);
84})
85// Stop network sharing.
86sharing.stopSharing(this.sharingType,(err)=>{
87    this.callBack(err);
88})
89```
90
91### Initiating a Network Request
92
931. Import the **http** namespace from **@ohos.net.http.d.ts**.
942. Call **createHttp()** to create an **HttpRequest** object.
953. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
964. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
975. Parse the returned result based on service requirements.
986. Call **off()** to unsubscribe from HTTP response header events.
997. Call **httpRequest.destroy()** to release resources after the request is processed.
100
101```
102// Import the http namespace.
103import http from '@ohos.net.http';
104
105// Each httpRequest corresponds to an HTTP request task and cannot be reused.
106let httpRequest = http.createHttp();
107// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
108// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
109httpRequest.on('headersReceive', (header) => {
110    console.info('header: ' + JSON.stringify(header));
111});
112httpRequest.request(
113    // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
114    "EXAMPLE_URL",
115    {
116        method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
117        // You can add header fields based on service requirements.
118        header: {
119            'Content-Type': 'application/json'
120        },
121        // This field is used to transfer data when the POST request is used.
122        extraData: {
123            "data": "data to send",
124        },
125        expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
126        usingCache: true, // Optional. The default value is true.
127        priority: 1, // Optional. The default value is 1.
128        connectTimeout: 60000 // Optional. The default value is 60000, in ms.
129        readTimeout: 60000, // Optional. The default value is 60000, in ms.
130        usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
131        usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
132    }, (err, data) => {
133        if (!err) {
134            // data.result carries the HTTP response. Parse the response based on service requirements.
135            console.info('Result:' + JSON.stringify(data.result));
136            console.info('code:' + JSON.stringify(data.responseCode));
137            // data.header carries the HTTP response header. Parse the content based on service requirements.
138            console.info('header:' + JSON.stringify(data.header));
139            console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
140        } else {
141            console.info('error:' + JSON.stringify(err));
142            // Unsubscribe from HTTP Response Header events.
143            httpRequest.off('headersReceive');
144            // Call the destroy() method to release resources after HttpRequest is complete.
145            httpRequest.destroy();
146        }
147    }
148);
149```
150
151## Repositories Involved
152
153**Network Management Subsystem**
154
155[communication_netmanager_base](https://gitee.com/openharmony/communication_netmanager_base/blob/master/README_zh.md)
156[communication_netmanager_ext](https://gitee.com/openharmony/communication_netmanager_ext/blob/master/README_zh.md)
157[communication_netstack](https://gitee.com/openharmony/communication_netstack/blob/master/README_zh.md)
158