The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
> **NOTE**<br>
>**NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
## Modules to Import
## Modules to Import
...
@@ -11,9 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca
...
@@ -11,9 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca
importhttpfrom'@ohos.net.http';
importhttpfrom'@ohos.net.http';
```
```
## Example
## Examples
```js
```js
// Import the HTTP namespace.
importhttpfrom'@ohos.net.http';
importhttpfrom'@ohos.net.http';
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300007 | Couldn't connect to server. |
| 2300028 | Timeout was reached. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300999 | Unknown Other Error. |
>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300007 | Couldn't connect to server. |
| 2300028 | Timeout was reached. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300999 | Unknown Other Error. |
>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
Unregisters the observer for events indicating receiving of HTTP streaming responses.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
Unregisters the observer for events indicating completion of receiving HTTP streaming responses.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void
Unregisters the observer for events indicating progress of receiving HTTP streaming responses.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
| type | string | Yes | Event type. The value is **dataProgress**.|
| callback | Callback\<{ receiveSize: number, totalSize: number }\> | No | Callback used to return the result. |
**Example**
```js
httpRequest.off('dataProgress');
```
## HttpRequestOptions
## HttpRequestOptions
Specifies the type and value range of the optional parameters in the HTTP request.
Specifies the type and value range of the optional parameters in the HTTP request.
...
@@ -364,6 +809,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques
...
@@ -364,6 +809,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. |
| usingProxy<sup>10+</sup> | boolean \| Object | No | Whether to use HTTP proxy. The default value is **false**, which means not to use HTTP proxy.<br>- If **usingProxy** is of the **Boolean** type and the value is **true**, network proxy is used by default.<br>- If **usingProxy** is of the **object** type, the specified network proxy is used. |
## RequestMethod
## RequestMethod
...
@@ -372,7 +818,7 @@ Defines an HTTP request method.
...
@@ -372,7 +818,7 @@ Defines an HTTP request method.
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. |
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. |
| responseCode | [ResponseCode](#responsecode)\| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).|
| responseCode | [ResponseCode](#responsecode)\| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**.|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
| cookies<sup>8+</sup> | string | Yes | Cookies returned by the server. |
## http.createHttpResponseCache<sup>9+</sup>
## http.createHttpResponseCache<sup>9+</sup>
...
@@ -457,7 +903,7 @@ Creates a default object to store responses to HTTP access requests.
...
@@ -457,7 +903,7 @@ Creates a default object to store responses to HTTP access requests.
| -1 | Incorrect parameter. Check whether the number and type of parameters are correct. |
| 3 | Incorrect URL format. Check whether the format and syntax of the URL are correct. |
| 4 | Built-in request function, protocol, or option not found during build. If a function or option is not enabled or explicitly disabled, you need to rebuild a libcurl in order to access its functions. |
| 5 | Unable to resolve the proxy because of a failure to resolve the specified proxy server. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 6 | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 7 | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host. |
For details about the error codes, see [Curl Error Codes] (https://curl.se/libcurl/c/libcurl-errors.html).
The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
> **NOTE**<br>
> **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
| iface | string | Yes | Name of the network interface. |
| iface | string | Yes | Interface name. |
| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. |
| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.|
| Promise\<void> | Promise that returns no value.|
| Promise\<void> | Promise used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.|
| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. |
| iface | string | Yes | Interface name. If this parameter is left empty, the API checks for any active network interface. |
| callback | AsyncCallback\<number> | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.|
| callback | AsyncCallback\<number> | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.|
| Promise\<number> | Promise used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.|
| Promise\<number> | Promise used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.|
| mode | [IPSetMode](#ipsetmode) | Yes | Configuration mode of the Ethernet connection.|
| Name | Type | Mandatory| Description |
| ipAddr | string | Yes | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.|
| route | string | Yes | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| mode | [IPSetMode](#ipsetmode) | Yes| Configuration mode of the Ethernet connection.|
| gateway | string | Yes | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| ipAddr | string | Yes| Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.|
| netMask | string | Yes | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| route | string | Yes| Route of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | Yes | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).|
| gateway | string | Yes| Gateway of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| netMask | string | Yes| Subnet mask of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | Yes| DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).|
## IPSetMode
## IPSetMode
Defines the configuration mode of the Ethernet connection.
Defines the configuration mode of the Ethernet connection.
The **sharing** module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
The **sharing** module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
## Modules to Import
...
@@ -29,6 +30,15 @@ Checks whether network sharing is supported. This API uses an asynchronous callb
...
@@ -29,6 +30,15 @@ Checks whether network sharing is supported. This API uses an asynchronous callb
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
@@ -140,11 +175,27 @@ Starts network sharing of a specified type. This API uses an asynchronous callba
...
@@ -140,11 +175,27 @@ Starts network sharing of a specified type. This API uses an asynchronous callba
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
@@ -203,11 +270,25 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac
...
@@ -203,11 +270,25 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
@@ -495,11 +660,22 @@ Obtains the network sharing state of the specified type. This API uses an asynch
...
@@ -495,11 +660,22 @@ Obtains the network sharing state of the specified type. This API uses an asynch
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.|
| callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.|
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
@@ -559,11 +746,22 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
...
@@ -559,11 +746,22 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return an array of regular expressions.|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return an array of regular expressions.|
@@ -679,12 +900,18 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an
...
@@ -679,12 +900,18 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an
| type | string | Yes | Event name.|
| type | string | Yes | Event name.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used to return the result.|
The **socket** module implements socket connection management and operation.
> **NOTE**
>
> **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
| Promise\<void\> | Promise used to return the result.|
| Promise\<void\> | Promise used to return the result.|
**Example**
**Example**
...
@@ -123,6 +135,13 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
...
@@ -123,6 +135,13 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
**Example**
```js
```js
...
@@ -162,10 +181,17 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
...
@@ -162,10 +181,17 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
@@ -346,6 +378,12 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous
...
@@ -346,6 +378,12 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
udp.off('listening',callback1);
udp.off('listening',callback1);
udp.off('listening');
udp.off('listening');
letcallback2=()=>{
letcallback2=()=>{
console.log("on close, success");
console.log("on close, success");
}
}
udp.on('close',callback2);
udp.on('close',callback2);
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
udp.off('close',callback2);
udp.off('close',callback2);
udp.off('close');
udp.off('close');
```
```
...
@@ -563,7 +608,6 @@ Enables listening for error events of the UDPSocket connection. This API uses an
...
@@ -563,7 +608,6 @@ Enables listening for error events of the UDPSocket connection. This API uses an
| type | string | Yes | Type of the event to subscribe to.<br/>**error**: error event|
| type | string | Yes | Type of the event to subscribe to.<br/>**error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. |
| callback | ErrorCallback | Yes | Callback used to return the result. |
Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
udp.off('error',callback);
udp.off('error',callback);
udp.off('error');
udp.off('error');
```
```
...
@@ -668,6 +712,12 @@ Defines information about the socket connection.
...
@@ -668,6 +712,12 @@ Defines information about the socket connection.
| port | number | Yes | Port number. The value ranges from **0** to **65535**. |
| port | number | Yes | Port number. The value ranges from **0** to **65535**. |
| size | number | Yes | Length of the server response message, in bytes. |
| size | number | Yes | Length of the server response message, in bytes. |
## Description of UDP Error Codes
The UDP error code mapping is in the format of 2301000 + Linux kernel error code.
For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md).
## socket.constructTCPSocketInstance
## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket
constructTCPSocketInstance\(\): TCPSocket
...
@@ -679,7 +729,7 @@ Creates a **TCPSocket** object.
...
@@ -679,7 +729,7 @@ Creates a **TCPSocket** object.
@@ -846,6 +923,13 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t
...
@@ -846,6 +923,13 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
@@ -1150,6 +1274,13 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous
...
@@ -1150,6 +1274,13 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcp.off('message',callback);
tcp.off('message',callback);
tcp.off('message');
tcp.off('message');
```
```
...
@@ -1305,7 +1442,6 @@ Enables listening for connection or close events of the TCPSocket connection. Th
...
@@ -1305,7 +1442,6 @@ Enables listening for connection or close events of the TCPSocket connection. Th
| type | string | Yes | Type of the event to subscribe to.<br/><br>- **connect**: connection event<br>- **close**: close event|
| type | string | Yes | Type of the event to subscribe to.<br/><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. |
| callback | Callback\<void\> | Yes | Callback used to return the result. |
Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcp.off('connect',callback1);
tcp.off('connect',callback1);
tcp.off('connect');
tcp.off('connect');
letcallback2=()=>{
letcallback2=()=>{
console.log("on close success");
console.log("on close success");
}
}
tcp.on('close',callback2);
tcp.on('close',callback2);
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcp.off('error',callback);
tcp.off('error',callback);
tcp.off('error');
tcp.off('error');
```
```
...
@@ -1452,7 +1588,13 @@ Defines other properties of the TCPSocket connection.
...
@@ -1452,7 +1588,13 @@ Defines other properties of the TCPSocket connection.
| receiveBufferSize | number | No | Size of the receive buffer, in bytes. |
| receiveBufferSize | number | No | Size of the receive buffer, in bytes. |
| sendBufferSize | number | No | Size of the send buffer, in bytes. |
| sendBufferSize | number | No | Size of the send buffer, in bytes. |
| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. |
| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. |
| socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. |
| socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms. |
## Description of TCP Error Codes
The TCP error code mapping is in the format of 2301000 + Linux kernel error code.
For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md).
## socket.constructTLSSocketInstance<sup>9+</sup>
## socket.constructTLSSocketInstance<sup>9+</sup>
...
@@ -1465,7 +1607,7 @@ Creates a **TLSSocket** object.
...
@@ -1465,7 +1607,7 @@ Creates a **TLSSocket** object.
The **webSocket** module implements WebSocket connection management and operation.
> **NOTE**
> **NOTE**<br>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
...
@@ -17,7 +16,7 @@ If an error occurs in any of the preceding processes, the client will receive a
...
@@ -17,7 +16,7 @@ If an error occurs in any of the preceding processes, the client will receive a
importwebSocketfrom'@ohos.net.webSocket';
importwebSocketfrom'@ohos.net.webSocket';
```
```
## Complete Example
## Examples
```js
```js
importwebSocketfrom'@ohos.net.webSocket';
importwebSocketfrom'@ohos.net.webSocket';
...
@@ -37,7 +36,7 @@ ws.on('open', (err, value) => {
...
@@ -37,7 +36,7 @@ ws.on('open', (err, value) => {
});
});
ws.on('message',(err,value)=>{
ws.on('message',(err,value)=>{
console.log("on message, message:"+value);
console.log("on message, message:"+value);
// When receiving the bye message (the actual message name may differ) from the server, the client proactively disconnects from the server.
// When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
...
@@ -507,7 +559,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u
...
@@ -507,7 +559,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u
```js
```js
letws=webSocket.createWebSocket();
letws=webSocket.createWebSocket();
ws.on('close',(err,value)=>{
ws.on('close',(err,value)=>{
console.log("on close, code is "+value['code']+", reason is "+value['reason']);
console.log("on close, code is "+value.code+", reason is "+value.reason);
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
This error code is reported if an operation is not allowed.
**Cause**
The operation is illegal.
**Procedure**
Check the operation procedure.
## 2301002 File Not Exist
**Error Message**
No such file or directory.
**Description**
This error code is reported if the requested file does not exist.
**Cause**
The requested file does not exist.
**Procedure**
Check the file name or file path.
## 2301003 Process Not Exist
**Error Message**
No such process.
**Description**
This error code is reported if a process does not exist.
**Cause**
The process does not exist.
**Procedure**
Check the process information.
## 2301004 System Call Interrupted
**Error Message**
Interrupted system call.
**Description**
This error code is reported if the system call is interrupted.
**Cause**
The system call is interrupted.
**Procedure**
Rectify system call errors.
**Description of TCP/UDP error codes:**
> Mapping format of other TCP/UDP Socket error codes: 2301000 + Linux kernel error code (errno). For details, see Linux kernel error codes.
## 2300002 System Internal Error
**Error Message**
System internal error.
**Description**
This error code is reported if a system internal error occurs.
**Cause**
1. The memory is abnormal.
2. A null pointer is present.
**Procedure**
1. Check whether the memory space is sufficient. If not, clear the memory and try again.
2. Check whether the system is normal. If not, try again later or restart the device.
## 2303104 System Call Interrupted
**Error Message**
Interrupted system call.
**Description**
This error code is reported if the system call is interrupted.
**Cause**
Calling the **connect** function may result in a long blocking time. In such a case, the system generates an interrupt signal and returns an **EINTR** error.
**Procedure**
Call the **connect** function to try network connection again.
## 2303109 Error File Number
**Error Message**
Bad file number.
**Description**
This error code is reported if an operation is performed on a locally closed socket.
This error code is reported if the requested system resource is temporarily unavailable.
**Cause**
The system resources are in use.
**Procedure**
Try again later.
## 2303188 Socket Operations on Non-Sockets
**Error Message**
Socket operation on non-socket.
**Description**
This error code is reported if a socket descriptor is not specified for the **socket** parameter.
**Cause**
A socket descriptor is not specified for the **socket** parameter.
**Procedure**
Check whether the descriptor is correctly obtained.
## 2303191 Incorrect Socket Protocol Type
**Error Message**
Protocol wrong type for socket.
**Description**
This error code is reported if the type of the specified socket protocol is incorrect.
**Cause**
The **socket** function is called with an unsupported socket protocol type.
For example, the protocol type cannot be set to **SOCK_STREAM socket** for the the Internet UDP protocol.
**Procedure**
Check whether the socket protocol type is correct.
## 2303198 Network Address Already In Use
**Error Message**
Address already in use.
**Description**
This error code is reported if a network address has been used.
**Cause**
The probable cause can be any of the following: The application attempts to bind a socket to an IP address/port that has been used for an existing socket. The socket is not properly closed. The socket is still being closed.
**Procedure**
Try another network address.
## 2303199 Failed to Assign the Requested Address
**Error Message**
Cannot assign requested address.
**Description**
This error code is reported if the requested address is invalid in its context.
**Cause**
The remote address or port is invalid for the remote server.
**Procedure**
Check whether the address or port is correct.
## 2303210 Connection Timeout
**Error Message**
Connection timed out.
**Description**
This error code is reported if the connection to the remote server cannot be set up for a long time.
**Cause**
It is probable that a server breakdown has occurred.
**Procedure**
Contact the peer end to rectify the fault.
## 2303501 Null SSL
**Error Message**
SSL is null.
**Description**
This error code is reported if the SSL is null.
**Cause**
The returned error information is null when an internal function fails to be executed.
**Procedure**
Call the function again.
## 2303502 TLS Reading Error
**Error Message**
Error in tls reading.
**Description**
This error code is reported if an error occurs while reading data on the TLS socket.
**Cause**
The underlying socket is blocked.
**Procedure**
Perform data receiving again.
## 2303503 TLS Writing Error
**Error Message**
Error in tls writing.
**Description**
This error code is reported if an error occurs while writing data on the TLS socket.
**Cause**
When the send buffer is full, the underlying socket sends an **EWOUDLBLOCK** error, which means that the server does not read the data sent from the client.
**Procedure**
Rectify the fault on the server side.
## 2303504 x509 Failed to Look Up the x509 Certificate
**Error Message**
Error looking up x509.
**Description**
An error occurred when verifying the x509 certificate.
**Cause**
The local certificate does not match the server certificate.
**Procedure**
Check whether the local CA matches the server certificate.
## 2303505 TLS System Call Error
**Error Message**
Error occurred in the tls system call.
**Description**
This error code is reported if the TLS system call fails because of fatal I/O errors.
**Cause**
Network communication fails because of network faults.
**Procedure**
For details, see the Linux kernel error codes (errno).
## 2303506 Failed to Close TLS Connections
**Error Message**
Error clearing tls connection.
**Description**
This error code is reported if the TLS/SSL connection to be closed has been disabled.
**Cause**
The TLS/SSL connection to be closed has been disabled.