An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
...
@@ -15,39 +15,48 @@ For details about how to apply for permissions, see [Access Control Development]
...
@@ -15,39 +15,48 @@ For details about how to apply for permissions, see [Access Control Development]
The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
| request() | Initiates an HTTP request to a given URL. |
| request() | Initiates an HTTP request to a given URL. |
| request2()<sup>10+</sup> | Initiates an HTTP network request based on the URL and returns a streaming response.|
| destroy() | Destroys an HTTP request. |
| destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.|
| on\('dataReceive'\)<sup>10+</sup> | Registers an observer for events indicating receiving of HTTP streaming responses. |
| off\('dataReceive'\)<sup>10+</sup> | Unregisters the observer for events indicating receiving of HTTP streaming responses. |
| on\('dataEnd'\)<sup>10+</sup> | Registers an observer for events indicating completion of receiving HTTP streaming responses. |
| off\('dataEnd'\)<sup>10+</sup> | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.|
| on\('dataProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
| off\('dataProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop
## How to Develop
1. Import the required HTTP module.
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Create an **HttpRequest** object.
2. Call **createHttp()** to create an **HttpRequest** object.
3. (Optional) Listen for HTTP Response Header events.
3. 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.
4. Initiate an HTTP request to a given URL.
4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. (Optional) Process the HTTP Response Header event and the return result of the HTTP request.
5. Parse the returned result based on service requirements.
6. Call **off()** to unsubscribe from HTTP response header events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
```js
```js
// Import the http namespace.
importhttpfrom'@ohos.net.http';
importhttpfrom'@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
lethttpRequest=http.createHttp();
lethttpRequest=http.createHttp();
// 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.
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
httpRequest.on('headersReceive',(header)=>{
httpRequest.on('headersReceive',(header)=>{
console.info('header: '+JSON.stringify(header));
console.info('header: '+JSON.stringify(header));
});
});
httpRequest.request(
httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData.
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
"EXAMPLE_URL",
{
{
method:http.RequestMethod.POST,// Optional. The default value is http.RequestMethod.GET.
method:http.RequestMethod.POST,// Optional. The default value is http.RequestMethod.GET.
// You can add the header field based on service requirements.
// You can add header fields based on service requirements.
header:{
header:{
'Content-Type':'application/json'
'Content-Type':'application/json'
},
},
...
@@ -55,21 +64,33 @@ httpRequest.request(
...
@@ -55,21 +64,33 @@ httpRequest.request(
extraData:{
extraData:{
"data":"data to send",
"data":"data to send",
},
},
connectTimeout:60000,// Optional. The default value is 60000, in ms.
expectDataType:http.HttpDataType.STRING,// Optional. This field specifies the type of the return data.
usingCache:true,// Optional. The default value is true.
priority:1,// Optional. The default value is 1.
connectTimeout:60000// Optional. The default value is 60000, in ms.
readTimeout:60000,// Optional. The default value is 60000, in ms.
readTimeout:60000,// Optional. The default value is 60000, in ms.
usingProtocol:http.HttpProtocol.HTTP1_1,// Optional. The default protocol type is automatically specified by the system.
usingProxy:false,// Optional. By default, network proxy is not used. This field is supported since API 10.
},(err,data)=>{
},(err,data)=>{
if(!err){
if(!err){
// data.result contains the HTTP response. Parse the response based on service requirements.
// data.result carries the HTTP response. Parse the response based on service requirements.
The HiAppEvent module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
The **hiAppEvent** module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
> **NOTE**
> **NOTE**
>
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead.
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead.
> - 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.
...
@@ -19,7 +20,7 @@ Before using application event logging, you need to understand the requirements
...
@@ -19,7 +20,7 @@ Before using application event logging, you need to understand the requirements
**Event Name**
**Event Name**
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
**Event Type**
**Event Type**
...
@@ -30,9 +31,10 @@ An event type is an enumerated value of [EventType](#eventtype).
...
@@ -30,9 +31,10 @@ An event type is an enumerated value of [EventType](#eventtype).
An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows:
An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows:
- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
- The parameter value is a string, number, boolean, or array.
- The parameter value can be of the string, number, boolean, or array type.
- When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated.
- If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded.
- When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
- If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated.
- If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.
This module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration.
The **hiAppEvent** module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration.
> **NOTE**
> **NOTE**
>
>
...
@@ -121,11 +121,11 @@ Defines parameters for an **AppEventInfo** object.
...
@@ -121,11 +121,11 @@ Defines parameters for an **AppEventInfo** object.
| domain | string | Yes | Event domain. Event domain name, which is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| name | string | Yes | Event name.|
| name | string | Yes | Event name. Event name, which is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| params | object | Yes | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:<br>- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).<br>- The parameter value can be a string, number, boolean, or array. If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated. If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.<br>- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.|
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**.
This 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**
>**NOTE**
>
>
...
@@ -13,10 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca
...
@@ -13,10 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca
importhttpfrom'@ohos.net.http';
importhttpfrom'@ohos.net.http';
```
```
## Examples
## Example
```js
```js
// Import the HTTP namespace.
// 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.
@@ -513,7 +513,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
...
@@ -513,7 +513,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
>**NOTE**
>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> 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:
> 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).
**Example**
**Example**
...
@@ -839,7 +839,7 @@ Enumerates the response codes for an HTTP request.
...
@@ -839,7 +839,7 @@ Enumerates the response codes for an HTTP request.
// 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('message',callback);
udp.off('message',callback);
udp.off('message');
udp.off('message');
```
```
...
@@ -582,14 +582,14 @@ let callback1 = () =>{
...
@@ -582,14 +582,14 @@ let callback1 = () =>{
console.log("on listening, success");
console.log("on listening, success");
}
}
udp.on('listening',callback1);
udp.on('listening',callback1);
// 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.
// 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.
// 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');
```
```
...
@@ -1486,14 +1486,14 @@ let callback1 = () =>{
...
@@ -1486,14 +1486,14 @@ let callback1 = () =>{
console.log("on connect success");
console.log("on connect success");
}
}
tcp.on('connect',callback1);
tcp.on('connect',callback1);
// 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.
// 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.
> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.net.http`](js-apis-http.md) instead.
> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.net.http`](js-apis-http.md) instead.
>
>
> - The initial APIs of this module are supported since API version 3. 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 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...
@@ -15,7 +14,7 @@ import fetch from '@system.fetch';
...
@@ -15,7 +14,7 @@ import fetch from '@system.fetch';
```
```
## fetch.fetch
## fetch.fetch<sup>3+</sup>
fetch(Object): void
fetch(Object): void
...
@@ -31,9 +30,9 @@ Obtains data through a network.
...
@@ -31,9 +30,9 @@ Obtains data through a network.
| header | Object | No| Request header.|
| header | Object | No| Request header.|
| method | string | No| Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**.|
| method | string | No| Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**.|
| responseType | string | No| Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values in the **success** callback.|
| responseType | string | No| Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values in the **success** callback.|
| success | Function | No| Called when data is obtained successfully. The return value is [FetchResponse](#fetchresponse). |
| success | Function | No| Called when the API call is successful. The return value is defined by [FetchResponse](#fetchresponse).|
| fail | Function | No| Called when data failed to be obtained.|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when the execution is complete.|
| complete | Function | No| Called when the API call is complete.|
**Table 1** Mapping between data and Content-Type
**Table 1** Mapping between data and Content-Type
...
@@ -46,11 +45,11 @@ Obtains data through a network.
...
@@ -46,11 +45,11 @@ Obtains data through a network.
| data | string \| Object | The type of the returned data is determined by **responseType**. For details, see the mapping between **responseType** and **data** in **success** callback.|
| data | string \| Object | Yes| No| The type of the returned data is determined by **responseType**. For details, see the mapping between **responseType** and **data** in **success** callback.|
| headers | Object | All headers in the response from the server.|
| headers | Object | Yes| No| All headers in the response from the server.|
**Table 2** Mapping between responseType and data in success callback
**Table 2** Mapping between responseType and data in success callback
> HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. That is:
> HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. That is:
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation).
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation).
| timeout | number | No| Timeout duration, in ms. The default value is **30000**.<br>The timeout duration is necessary in case the request to obtain the geographic location is rejected for the lack of the required permission, weak positioning signal, or incorrect location settings. After the timeout duration expires, the fail function will be called.<br>The value is a 32-digit positive integer. If the specified value is less than or equal to **0**, the default value will be used.|
| options | [GetLocationOption](#getlocationoptiondeprecated) | No| Options of a single location request.|
| coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.|
| success | Function | No| Called when API call is successful.|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when API call is complete.|
**Return value of success()**
| Name| Type| Description|
| -------- | -------- | -------- |
| longitude | number | Longitude.|
| latitude | number | Latitude.|
| altitude | number | Altitude.|
| accuracy | number | Location accuracy.|
| time | number | Time when the location is obtained.|
**Return value of fail()**
| Error Code| Description|
| -------- | -------- |
| 601 | Failed to obtain the required permission because the user rejected the request.|
| 602 | Permission not declared.|
| 800 | Operation times out due to a poor network condition or GNSS unavailability.|
| 801 | System location disabled.|
| 802 | API called again while the previous execution result is not returned yet.|
> This API is deprecated since API version 9. The location subsystem supports only two location types: GPS positioning and network positioning. No APIs will be provided to query the supported location types.
> This API is deprecated since API version 9. The location subsystem supports only two location types: GNSS positioning and network positioning. No APIs will be provided to query the supported location types.
@@ -93,15 +71,7 @@ Obtains the supported location types.
...
@@ -93,15 +71,7 @@ Obtains the supported location types.
| Name| Type| Mandatory| Description|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| success | Function | No| Called when API call is successful.|
| options | [GetLocationTypeOption](#getlocationtypeoptiondeprecated) | No| Callback used to return the result.|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when API call is complete.|
**Return value of success()**
| Name| Type| Description|
| -------- | -------- | -------- |
| types | Array<string> | Available location types, ['gps', 'network']|
**Example**
**Example**
...
@@ -123,40 +93,22 @@ export default {
...
@@ -123,40 +93,22 @@ export default {
## geolocation.subscribe<sup>(deprecated)</sup>
## geolocation.subscribe<sup>(deprecated)</sup>
subscribe(Object): void
subscribe(options: SubscribeLocationOption): void
Listens to the geographic location. If this method is called multiple times, the last call takes effect.
Listens to the geographic location. If this method is called multiple times, the last call takes effect.
> **NOTE**
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange).
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange).
| coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.|
| options | [SubscribeLocationOption](#subscribelocationoptiondeprecated) | Yes| Options for continuous location.|
| success | Function | Yes| Called when the geographic location changes.|
| fail | Function | No| Called when API call has failed.|
**Return value of success()**
| Name| Type| Description|
| -------- | -------- | -------- |
| longitude | number | Longitude.|
| latitude | number | Latitude.|
| altitude | number | Altitude.|
| accuracy | number | Location accuracy.|
| time | number | Time when the location is obtained.|
**Return value of fail()**
| Error Code| Description|
| -------- | -------- |
| 601 | Failed to obtain the required permission because the user rejected the request.|
| 602 | Permission not declared.|
| 801 | System location disabled.|
**Example**
**Example**
...
@@ -185,6 +137,8 @@ Cancels listening to the geographic location.
...
@@ -185,6 +137,8 @@ Cancels listening to the geographic location.
> **NOTE**
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange).
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange).
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#CurrentLocationRequest).
| timeout | number | No| Timeout duration, in ms. The default value is **30000**.<br>The timeout duration is necessary in case the request to obtain the geographic location is rejected for the lack of the required permission, weak positioning signal, or incorrect location settings. After the timeout duration expires, the fail function will be called.<br>The value is a 32-digit positive integer. If the specified value is less than or equal to **0**, the default value will be used.|
| coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.|
| success | (data: [GeolocationResponse](#geolocationresponsedeprecated)) => void | No| Called when API call is successful.|
| fail | (data: string, code: number) => void | No| Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.|
| complete | () => void | No| Called when API call is complete.|
**Return value of fail()**
| Error Code| Description|
| -------- | -------- |
| 601 | Failed to obtain the required permission because the user rejected the request.|
| 602 | Permission not declared.|
| 800 | Operation times out due to a poor network condition or GNSS unavailability.|
| 801 | System location disabled.|
| 802 | API called again while the previous execution result is not returned yet.|
## GeolocationResponse<sup>(deprecated)</sup>
Defines the location information, including the longitude, latitude, and location precision.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.Location](js-apis-geoLocationManager.md#location).
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#locationrequest).
> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.telephony.observer`](js-apis-observer.md).
>
>
> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead.
> - The initial APIs of this module are supported since API version 3. 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 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...
@@ -31,17 +31,17 @@ Obtains the network type.
...
@@ -31,17 +31,17 @@ Obtains the network type.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Description |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| success | Function | No | Called when the execution is successful. The return value is [NetworkResponse](#networkresponse). |
| success | Function | No| Called when the API call is successful. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No | Called when the operation fails. |
| fail | Function | No| Called when API call has failed.|
| complete | Function | No | Called when the execution is complete |
| complete | Function | No| Called when the API call is complete.|
Return value of the **fail** callback:
One of the following error codes will be returned if the API call has failed.
| Error Code | Description |
| Error Code| Description|
| -------- | -------- |
| -------- | -------- |
| 602 | The current permission is not declared.|
| 602 | The current permission is not declared.|
**Example**
**Example**
...
@@ -71,17 +71,17 @@ Listens to the network connection state. If this method is called multiple times
...
@@ -71,17 +71,17 @@ Listens to the network connection state. If this method is called multiple times
**Parameters**
**Parameters**
| Name | Type | Mandatory | Description |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| success | Function | No | Called when the network connection state changes |
| success | Function | No| Called when the network state changes. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No | Called when the multimedia volume fails to be obtained. |
| fail | Function | No| Called when API call has failed.|
Return value of the **fail** callback:
One of the following error codes will be returned if the API call has failed.
Creates a WebSocket connection. You can use this API to create or close a WebSocket connection, send data over it, or enable or disable listening for the **open**, **close**, **message**, and **error** events.
Creates a WebSocket connection. You can use this API to create or close a WebSocket connection, send data over it, or enable or disable listening for the **open**, **close**, **message**, and **error** events.
...
@@ -89,7 +89,7 @@ Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call
...
@@ -89,7 +89,7 @@ Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call
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.
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.|
| data | string \| ArrayBuffer | Yes | Data to send.<br>Only the string type is supported for API version 6 or earlier. Both the string and ArrayBuffer types are supported for API version 8 or later.|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
Sends data through a WebSocket connection. This API uses a promise to return the result.
Sends data through a WebSocket connection. This API uses a promise to return the result.
...
@@ -270,7 +270,7 @@ Sends data through a WebSocket connection. This API uses a promise to return the
...
@@ -270,7 +270,7 @@ Sends data through a WebSocket connection. This API uses a promise to return the
| Name| Type | Mandatory| Description |
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------ |
| ------ | ------ | ---- | ------------ |
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.|
| data | string \| ArrayBuffer | Yes | Data to send.<br>Only the string type is supported for API version 6 or earlier. Both the string and ArrayBuffer types are supported for API version 8 or later.|
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.
>**NOTE**
>**NOTE**
>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 version 6) or ArrayBuffer (API version 8).
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.
>**NOTE**
>**NOTE**
>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 version 6) or ArrayBuffer (API version 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.
| type | string | Yes | Event type. <br/>**close**: event indicating that a WebSocket connection has been closed.|
| type | string | Yes | Event type. <br/>**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{code:number,reason:string}> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<{ code: number, reason: string }\> | Yes | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
| type | string | Yes | Event type. <br/>**close**: event indicating that a WebSocket connection has been closed.|
| type | string | Yes | Event type. <br/>**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{code:number,reason:string}> | No | Callback used to return the result. |
| callback | AsyncCallback\<{ code: number, reason: string }\> | No | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
@@ -12,15 +12,13 @@ The HiTraceMeter subsystem consists of three parts:
...
@@ -12,15 +12,13 @@ The HiTraceMeter subsystem consists of three parts:
- hitrace CLI tool for data collection
- hitrace CLI tool for data collection
- smartperf tool for graphical data analysis
- smartperf tool for graphical data analysis
Wherein, HiTraceMeter APIs and the hitrace CLI tool run on the device side, and the smartperf tool runs on the PC side.
Wherein, HiTraceMeter APIs and the hitrace CLI tool run on the device side, and the smartperf tool runs on the PC side. HiTraceMeter APIs are provided in C++ and JS for event logging, which aims to generate the trace data necessary for performance tracing and analysis during the development process.
HiTraceMeter APIs are provided in C++ and JS for event logging, which aims to generate the trace data necessary for performance tracing and analysis during the development process.
The hitrace CLI tool is used to collect trace data. It captures trace data flows and saves the data as a text file.
The hitrace CLI tool is used to collect trace data. It captures trace data flows and saves the data as a text file.
The smartperf tool allows you to perform data analysis manually or use the analysis script for automated data analysis. If you want to get the data analysis done automatically, you need to supply the data file generated by the hitrace CLI tool as the input for the smartperf tool.
The smartperf tool allows you to perform data analysis manually or use the analysis script for automated data analysis. If you want to get the data analysis done automatically, you need to supply the data file generated by the hitrace CLI tool as the input for the smartperf tool.
Traces data is classified by trace tag or trace category. Generally, one device subsystem corresponds to one tag. The tag is passed as the **Tag** parameter to event logging APIs. When you use the hitrace CLI tool to collect trace data, only the trace data specified by the **Tag** parameter is collected. Trace data of applications is fixedly labeled as **APP Tag**, and therefore, no **Tag** parameter needs to be passed to JS APIs. The following is a list of trace tags supported by HiTraceMeter. You can view the tags in [hitrace_meter.h](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h).
Traces data is classified by trace tag or trace category. Generally, one device subsystem corresponds to one tag. The tag is passed as the **Tag** parameter to event logging APIs. When you use the hitrace CLI tool to collect trace data, only the trace data specified by the **Tag** parameter is collected. Trace data of applications is fixedly labeled as **APP Tag**, and therefore, no **Tag** parameter needs to be passed to JS APIs. The following is a list of trace tags supported by HiTraceMeter. You can view the tags in [hitrace_meter.h](https://gitee.com/openharmony/hiviewdfx_hitrace/blob/master/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h).
```cpp
```cpp
constexpruint64_tHITRACE_TAG_NEVER=0;// This tag is never enabled.
constexpruint64_tHITRACE_TAG_NEVER=0;// This tag is never enabled.
HiTraceMeter provides the hitrace CLI tool for capturing trace data in user mode and kernel mode, and provides C++ (innerkits) and JS (kits) APIs for event logging in user mode. Through extending kernel's ftrace functionality, HiTraceMeter can use the trace_marker node of ftrace to write the data, which is written into the user space by event logging APIs, to the kernel buffer. The following figure shows the basic HiTraceMeter architecture.
HiTraceMeter provides the hitrace CLI tool for capturing trace data in user mode and kernel mode, and provides C++ (innerkits) and JS (kits) APIs for event logging in user mode. Through extending kernel's ftrace functionality, HiTraceMeter can use the trace_marker node of ftrace to write the data, which is written into the user space by event logging APIs, to the kernel buffer. The following figure shows the basic HiTraceMeter architecture.
...
@@ -83,7 +81,6 @@ HiTraceMeter provides the hitrace CLI tool for capturing trace data in user mode
...
@@ -83,7 +81,6 @@ HiTraceMeter provides the hitrace CLI tool for capturing trace data in user mode
## Constraints
## Constraints
- The implementation of HiTraceMeter functions and APIs depends on the ftrace functionality, a framework provided by the kernel. It enables developers to add more trace functions via plug-ins. Therefore, make sure that ftrace is enabled before you use HiTraceMeter.
- The implementation of HiTraceMeter functions and APIs depends on the ftrace functionality, a framework provided by the kernel. It enables developers to add more trace functions via plug-ins. Therefore, make sure that ftrace is enabled before you use HiTraceMeter.
...
@@ -98,7 +95,6 @@ HiTraceMeter development focuses on two parts: JS/C++ event logging APIs and the
...
@@ -98,7 +95,6 @@ HiTraceMeter development focuses on two parts: JS/C++ event logging APIs and the
## When to Use
## When to Use
You may encounter unexpected issues like app freezing during app development or need to view the code's call chain during code debugging. With the APIs provided by HiTraceMeter, you'll be able to trace the application delay and call chain to identify performance problems.
You may encounter unexpected issues like app freezing during app development or need to view the code's call chain during code debugging. With the APIs provided by HiTraceMeter, you'll be able to trace the application delay and call chain to identify performance problems.
...
@@ -109,18 +105,17 @@ Only C++ APIs are now open for system developers. If you're developing a JS app,
...
@@ -109,18 +105,17 @@ Only C++ APIs are now open for system developers. If you're developing a JS app,
| void StartTrace(uint64_t label, const std::string& value, float limit = -1); | Starts a synchronous trace.|**label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.|
| void StartTrace(uint64_t label, const std::string& value, float limit = -1); | Starts a synchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.|
**StartTrace** and **FinishTrace** must be used in pairs, and **FinishTrace** matches the latest **StartTrace**. The two APIs can be used in nested mode. The stack data structure is used for matching during trace data parsing. The **limit** parameter is used for flow control, and you are advised to use the default value.
**StartTrace** and **FinishTrace** must be used in pairs, and **FinishTrace** matches the latest **StartTrace**. The two APIs can be used in nested mode. The stack data structure is used for matching during trace data parsing. The **limit** parameter is used for flow control, and you are advised to use the default value.
**Table 2** Async APIs
**Table 2** Async APIs
| API | Function |Parameter Description |
| Async trace | Function | Parameter Description |
| void StartAsyncTrace(uint64_t label, const std::string& value, int32_t taskId, float limit = -1); | Starts an asynchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.<br>**taskId**: ID used to indicate the association of APIs in an asynchronous trace.|
| void StartAsyncTrace(uint64_t label, const std::string& value, int32_t taskId, float limit = -1); | Starts an asynchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.<br>**taskId**: ID used to indicate the association of APIs in an asynchronous trace.|
| void FinishAsyncTrace(uint64_t label, const std::string& value, int32_t taskId); | Stops an asynchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.<br>**taskId**: ID used to indicate the association of APIs in an asynchronous trace.|
| void FinishAsyncTrace(uint64_t label, const std::string& value, int32_t taskId); | Stops an asynchronous trace.| **label**: trace category.<br>**value**: trace data that indicates the specific status, such as the memory size and queue length.<br>**taskId**: ID used to indicate the association of APIs in an asynchronous trace.|
...
@@ -130,57 +125,32 @@ The trace data of **StartAsyncTrace** and **FinishAsyncTrace** is matched based
...
@@ -130,57 +125,32 @@ The trace data of **StartAsyncTrace** and **FinishAsyncTrace** is matched based
**Table 3** Counter APIs
**Table 3** Counter APIs
| API | Function |Parameter Description |
| Counter Trace | Function | Parameter Description |
| void CountTrace(uint64_t label, const std::string& name, int64_t); | Performs a count trace.|**label**: trace category.<br>**name**: trace name displayed in the IDE.|
| void CountTrace(uint64_t label, const std::string& name, int64_t); | Count trace.| **label**: trace category.<br>**name**: trace name displayed in the IDE.|
## How to Develop
## How to Develop
1. Add the build dependencies to the build configuration file **base\hiviewdfx\hitrace\cmd\BUILD.gn**.
1. Add the build dependencies to the build configuration file **base\hiviewdfx\hitrace\cmd\BUILD.gn**.
```
```
external_deps = [ "hitrace_native:hitrace_meter"]
external_deps = [ "hitrace_native:hitrace_meter"]
```
```
2. Add the header file dependencies.
2. Add the header file dependencies.
```cpp
```cpp
#include "hitrace_meter.h"// Header file for defining APIs
#include "hitrace_meter.h"// Header file for defining APIs
```
```
3. When calling an API, pass the trace value as an input parameter. After the hitrace command is executed in the shell, the trace data is automatically captured. The captured data includes the function call process and the memory and time consumed during this process. You can use the data to analyze the call process to identify performance problems.
3. When calling an API, pass the trace value as an input parameter. The trace tags currently supported are listed in **hitrace_meter.h**. Assume that the trace tag is **OHOS** and trace data of **func1** and **func2** needs to be captured. After the hitrace command is executed in the shell, the trace data is automatically captured. The captured data includes the function call process and the memory and time consumed during this process. You can use the data to analyze the call process to identify performance problems.
```cpp
```cpp
#include "hitrace_meter.h" // Include hitrace_meter.h
StartTrace(label, "func1Trace", -1); // Trace start point of func1Start
FinishTrace(label); // Trace end point of func1Trace
StartAsyncTrace(label, "asyncTrace1", 1234); // Start point of asyncTrace1
FinishAsyncTrace(label, "asyncTrace2", 3456); // End point of asyncTrace2
```
4. On completion of HiTraceMeter building and deployment, start a trace. After you run the application in the shell on the device, trace data will be captured automatically.
You can open the captured data by clicking **Open trace file** in the smartperf tool or dragging the data to the graphics area. For details, see [smartperf](https://toscode.gitee.com/openharmony-sig/smartperf).
## Development Example
You can access a full list of trace tags supported by HiTraceMeter in **hitrace_meter.h**. The following uses the **OHOS** tag as an example to illustrate how to obtain the trace data of the **func1** and **func2** functions.
```cpp
#include "hitrace_meter.h" // Include hitrace_meter.h
FinishTrace(label);// Trace end point of func1Trace
FinishTrace(label);// Trace end point of func1Trace
StartAsyncTrace(label,"asyncTrace1",1234);// Trace start point of asyncTrace1
FinishAsyncTrace(label,"asyncTrace1",1234);// Trace end point of asyncTrace1
return0;
return0;
}
}
```
```
4. On completion of HiTraceMeter building and deployment, start a trace. After you run the application in the shell on the device, trace data will be captured automatically.
You can open the captured data by clicking **Open trace file** in the smartperf tool or dragging the data to the graphics area. For details, see [smartperf](https://toscode.gitee.com/openharmony-sig/smartperf).
## Verification
## Verification
...
@@ -292,10 +271,10 @@ The hitrace CLI tool is an executable binary program. On an OpenHarmony-powered
...
@@ -292,10 +271,10 @@ The hitrace CLI tool is an executable binary program. On an OpenHarmony-powered
| -b *n*, --buffer_size *n* | Sets the buffer size for trace data in KB. The default value is **2048**. |
| -b *n*, --buffer_size *n* | Sets the buffer size for trace data in KB. The default value is **2048**. |
| -t *n*, --time *n* | Sets the trace uptime in seconds, which depends on the time required for analysis.|
| -t *n*, --time *n* | Sets the trace uptime in seconds, which depends on the time required for analysis.|
| --trace_clock clock | Sets the type of the clock for adding a timestamp to a trace. The value can be **boot** (default), **global**, **mono**, **uptime**, or **perf**.|
| --trace_clock clock | Sets the type of the clock for adding a timestamp to a trace. The value can be **boot** (default), **global**, **mono**, **uptime**, or **perf**.|
| --trace_begin | Starts capturing trace data. |
| --trace_begin | Starts capturing trace data. |
| --trace_dump | Dumps trace data to the specified position. The default position is the console. |
| --trace_dump | Dumps trace data to the specified position. The default position is the console. |
...
@@ -310,34 +289,41 @@ Examples:
...
@@ -310,34 +289,41 @@ Examples:
- Query supported labels.
- Query supported labels.
```
```
hitrace -l
hitrace -l
```
```
Or,
Alternatively, run the following command:
```
```
hitrace --list_categories
hitrace --list_categories
```
```
- Trace ability information for 10 seconds and store the trace data in a buffer of 4 MB.
- Trace ability information for 10 seconds and store the trace data in a buffer of 4 MB.
The data captured by running the hitrace command is incomplete or no data is captured.
The data captured by running the hitrace command is incomplete or no data is captured.
#### **Root Cause**
The value of **-t** or **-b** buffer is too small, leading to data loss.
#### Solution
#### Solution
Check the value of the **-t** and **-b** parameters. If the value is too small, data loss will occur. You are advised to set **-t** to **60** and **-b** to **204800** to increase the trace capture time and buffer, respectively.
You can set **-t** to **60** and **-b** to **204800** to increase the trace time and buffer size.
# References
# Reference
For details about HiTraceMeter, see [hiviewdfx_hitrace: A Lightweight Distributed Tracing](https://gitee.com/openharmony/hiviewdfx_hitrace).
For details about HiTraceMeter, see [hiviewdfx_hitrace: Lightweight Distributed Tracing](https://gitee.com/openharmony/hiviewdfx_hitrace).