未验证 提交 3bed0cd4 编写于 作者: O openharmony_ci 提交者: Gitee

!16502 翻译已完成15595+15911+15694+15884+16008

Merge pull request !16502 from shawn_he/15595-b
# HTTP Data Request
## Use Cases
## When to Use
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]
The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
| API | Description |
| ----------------------------------------- | --------------------------------------------------------- |
| ----------------------------------------- | ----------------------------------- |
| createHttp() | Creates an HTTP request. |
| 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. |
| 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
1. Import the required HTTP module.
2. Create an **HttpRequest** object.
3. (Optional) Listen for HTTP Response Header events.
4. Initiate an HTTP request to a given URL.
5. (Optional) Process the HTTP Response Header event and the return result of the HTTP request.
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
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. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters 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
// Import the http namespace.
import http from '@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.
let httpRequest = http.createHttp();
// 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) will be replaced by on('headersReceive', Callback) in API version 8. 8+
// 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.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
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",
{
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: {
'Content-Type': 'application/json'
},
......@@ -55,21 +64,33 @@ httpRequest.request(
extraData: {
"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.
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) => {
if (!err) {
// data.result contains the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header contains the HTTP response header. Parse the content based on service requirements.
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// Call the destroy() method to destroy the request if it is no longer needed.
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
}
);
```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`HTTP`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
......@@ -49,6 +49,7 @@ TLS Socket connection functions are mainly provided by the **tls_socket** module
| API| Description|
| -------- | -------- |
| constructTLSSocketInstance() | Creates a **TLSSocket** object.|
| bind() | Binds the IP address and port number.|
| close(type:&nbsp;'error') | Closes a Socket connection.|
| connect() | Sets up a connection to the specified IP address and port number.|
......@@ -189,7 +190,7 @@ TLS Socket connection process on the client:
let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
......@@ -199,10 +200,10 @@ TLS Socket connection process on the client:
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
tlsTwoWay.on('close', () => {
console.log("on close")
});
......@@ -245,23 +246,23 @@ TLS Socket connection process on the client:
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
// Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
......@@ -271,10 +272,10 @@ TLS Socket connection process on the client:
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
tlsTwoWay.on('close', () => {
console.log("on close")
});
......@@ -306,16 +307,16 @@ TLS Socket connection process on the client:
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
```
......
# @ohos.hiAppEvent (Application Event Logging)
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**
>
> - 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.
......@@ -19,7 +20,7 @@ Before using application event logging, you need to understand the requirements
**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**
......@@ -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:
- 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.
- When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated.
- 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.
- The parameter value can be of the string, number, boolean, or array type.
- 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.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.
**Event Callback**
......
# @ohos.hiviewdfx.hiAppEvent (Application Event Logging)
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**
>
......@@ -121,11 +121,11 @@ Defines parameters for an **AppEventInfo** object.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ---------- |
| domain | string | Yes | Event domain.|
| name | string | Yes | Event name.|
| eventType | [EventType](#eventtype) | Yes | Event type.|
| params | object | Yes | Event parameters.|
| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| 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. 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 (_).|
| eventType | [EventType](#eventtype) | Yes | Event type. |
| 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.|
## hiAppEvent.configure
......
# @ohos.net.http (Data Request)
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**
>
......@@ -13,10 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca
import http from '@ohos.net.http';
```
## Examples
## Example
```js
// Import the HTTP namespace.
// Import the http namespace.
import http from '@ohos.net.http';
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
......@@ -27,7 +27,7 @@ httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
// Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
......@@ -112,7 +112,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
**Error codes**
| ID | Error Message |
| Code | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -164,7 +164,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Error codes**
| ID | Error Message |
| Code | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -231,7 +231,7 @@ httpRequest.request("EXAMPLE_URL",
request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result.
Initiates an HTTP request to a given URL. This API uses a promise to return the result.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
......@@ -255,7 +255,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Error codes**
| ID | Error Message |
| Code | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -349,7 +349,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
**Error codes**
| ID | Error Message |
| Code | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -395,7 +395,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
**Error codes**
| ID | Error Message |
| Code | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -477,7 +477,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Error codes**
| ID | Error Message |
| Code | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -513,7 +513,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
>**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:
> 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**
......@@ -839,7 +839,7 @@ Enumerates the response codes for an HTTP request.
| Name | Value | Description |
| ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. |
| OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. |
| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. |
| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. |
| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
......
# # @ohos.net.socket (Socket Connection)
# Socket Connection
The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSocket, and TLSSocket connections.
......@@ -364,7 +364,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void
Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result.
Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>This API can be called only after **bind** is successfully called.
......@@ -418,7 +418,7 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> {
setExtraOptions(options: UDPExtraOptions): Promise\<void\>
Sets other attributes of the UDPSocket connection. This API uses a promise to return the result.
Sets other properties of the UDPSocket connection. This API uses a promise to return the result.
>**NOTE**
>This API can be called only after **bind** is successfully called.
......@@ -522,7 +522,7 @@ let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback);
// 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');
```
......@@ -582,14 +582,14 @@ let callback1 = () =>{
console.log("on listening, success");
}
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');
let callback2 = () =>{
console.log("on close, success");
}
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');
```
......@@ -646,7 +646,7 @@ let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
udp.on('error', callback);
// 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');
```
......@@ -1426,7 +1426,7 @@ let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
tcp.on('message', callback);
// 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');
```
......@@ -1486,14 +1486,14 @@ let callback1 = () =>{
console.log("on connect success");
}
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');
let callback2 = () =>{
console.log("on close success");
}
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.
tcp.off('close', callback2);
tcp.off('close');
```
......@@ -1550,7 +1550,7 @@ let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
tcp.on('error', callback);
// 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');
```
......
# @system.fetch (Data Request)
> **NOTE**
>
> - 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.
......@@ -15,7 +14,7 @@ import fetch from '@system.fetch';
```
## fetch.fetch
## fetch.fetch<sup>3+</sup>
fetch(Object): void
......@@ -31,9 +30,9 @@ Obtains data through a network.
| 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**.|
| 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). |
| fail | Function | No| Called when data failed to be obtained.|
| complete | Function | No| Called when the execution is complete.|
| success | Function | No| Called when the API call is successful. The return value is defined by [FetchResponse](#fetchresponse).|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when the API call is complete.|
**Table 1** Mapping between data and Content-Type
......@@ -46,11 +45,11 @@ Obtains data through a network.
## FetchResponse
| Name| Type| Description|
| -------- | -------- | -------- |
| code | number | Server status code.|
| 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.|
| headers | Object | All headers in the response from the server.|
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| code | number | Yes| No| Server status code.|
| 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 | Yes| No| All headers in the response from the server.|
**Table 2** Mapping between responseType and data in success callback
......@@ -85,7 +84,7 @@ export default {
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> **NOTE**
> 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:
>
> ```
......
......@@ -21,44 +21,22 @@ ohos.permission.LOCATION
## geolocation.getLocation<sup>(deprecated)</sup>
getLocation(Object): void
getLocation(options?: GetLocationOption): void
Obtains the geographic location.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Lite
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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 | 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.|
| options | [GetLocationOption](#getlocationoptiondeprecated) | No| Options of a single location request.|
**Example**
......@@ -80,12 +58,12 @@ export default {
## geolocation.getLocationType<sup>(deprecated)</sup>
getLocationType(Object): void
getLocationType(options?: GetLocationTypeOption): void
Obtains the supported location types.
> **NOTE**
> 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.
**System capability**: SystemCapability.Location.Location.Lite
......@@ -93,15 +71,7 @@ Obtains the supported location types.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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|
| -------- | -------- | -------- |
| types | Array&lt;string&gt; | Available location types, ['gps', 'network']|
| options | [GetLocationTypeOption](#getlocationtypeoptiondeprecated) | No| Callback used to return the result.|
**Example**
......@@ -123,40 +93,22 @@ export default {
## 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.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Lite
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.|
| 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.|
| options | [SubscribeLocationOption](#subscribelocationoptiondeprecated) | Yes| Options for continuous location.|
**Example**
......@@ -185,6 +137,8 @@ Cancels listening to the geographic location.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Lite
**Example**
......@@ -224,3 +178,102 @@ export default {
},
}
```
## GetLocationOption<sup>(deprecated)</sup>
Defines the options of a single location request.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#CurrentLocationRequest).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Lite
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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).
**System capability**: SystemCapability.Location.Location.Lite
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| longitude | number | Yes| No| Longitude.|
| latitude | number | Yes| No| Latitude.|
| altitude | number | Yes| No| Altitude.|
| accuracy | number | Yes| No| Location accuracy.|
| time | number | Yes| No| Time when the location is obtained.|
## GetLocationTypeOption<sup>(deprecated)</sup>
Defines the location type option, which holds the callback function used to return the query result.
> **NOTE**
> This API is deprecated since API version 9.
**System capability**: SystemCapability.Location.Location.Lite
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| success | (data: [GetLocationTypeResponse](#getlocationtyperesponsedeprecated)) => void | No| Called when API call is successful.|
| fail | (data: string, code: number) => void | No| Called when API call has failed.|
| complete | () => void | No| Called when API call is complete.|
## GetLocationTypeResponse<sup>(deprecated)</sup>
Defines the list of location types supported by the current device
> **NOTE**
> This API is deprecated since API version 9.
**System capability**: SystemCapability.Location.Location.Lite
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| types | Array&lt;string&gt; | Yes| No| Available location types, ['gps', 'network']|
## SubscribeLocationOption<sup>(deprecated)</sup>
Defines the options for continuous location.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#locationrequest).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Lite
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.|
| success | (data: [GeolocationResponse](#geolocationresponsedeprecated)) => void | Yes| Called when the geographic location changes.|
| fail | (data: string, code: number) => void | No| Called when API call has failed.|
**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.|
# @system.network (Network State)
> **NOTE**
> - 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.
......@@ -31,17 +31,17 @@ Obtains the network type.
**Parameters**
| Name | Type | Mandatory | Description |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| success | Function | No | Called when the execution is successful. The return value is [NetworkResponse](#networkresponse). |
| fail | Function | No | Called when the operation fails. |
| complete | Function | No | Called when the execution is complete |
| success | Function | No| Called when the API call is successful. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No| Called when API call has failed.|
| 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**
......@@ -71,17 +71,17 @@ Listens to the network connection state. If this method is called multiple times
**Parameters**
| Name | Type | Mandatory | Description |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| success | Function | No | Called when the network connection state changes |
| fail | Function | No | Called when the multimedia volume fails to be obtained. |
| success | Function | No| Called when the network state changes. The return value is defined by [NetworkResponse](#networkresponse).|
| 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.
| Error Code | Description |
| Error Code| Description|
| -------- | -------- |
| 602 | The current permission is not declared. |
| 200 | The subscription fails. |
| 602 | The current permission is not declared.|
| 200 | Subscription failed.|
**Example**
......@@ -119,9 +119,12 @@ export default {
}
```
## NetworkResponse
| Parameter | Type | Description |
| -------- | -------- | -------- |
| metered | boolean | Whether the billing is based on the data volume. |
| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. |
\ No newline at end of file
**System capability**: SystemCapability.Communication.NetManager.Core
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| metered | boolean | No|Whether to charge by traffic.|
| type | string | Yes|Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**.|
......@@ -64,7 +64,7 @@ ws.connect(defaultIpAddress, (err, value) => {
## webSocket.createWebSocket
createWebSocket\(\): WebSocket
createWebSocket(): WebSocket
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
### connect
connect\(url: string, callback: AsyncCallback<boolean\>\): void
connect(url: string, callback: AsyncCallback\<boolean\>): void
Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
......@@ -128,7 +128,7 @@ ws.connect(url, (err, value) => {
### connect
connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback<boolean\>\): void
connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void
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.
......@@ -173,7 +173,7 @@ ws.connect(url, {
### connect
connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\>
connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\>
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.
......@@ -217,7 +217,7 @@ promise.then((value) => {
### send
send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void
send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -229,7 +229,7 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac
| 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.|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Error codes**
......@@ -258,7 +258,7 @@ ws.connect(url, (err, value) => {
### send
send\(data: string | ArrayBuffer\): Promise<boolean\>
send(data: string | ArrayBuffer): Promise\<boolean\>
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
| 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.|
**Return value**
......@@ -303,7 +303,7 @@ ws.connect(url, (err, value) => {
### close
close\(callback: AsyncCallback<boolean\>\): void
close(callback: AsyncCallback\<boolean\>): void
Closes a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -341,7 +341,7 @@ ws.close((err, value) => {
### close
close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void
close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result.
......@@ -383,7 +383,7 @@ ws.close({
### close
close\(options?: WebSocketCloseOptions\): Promise<boolean\>
close(options?: WebSocketCloseOptions): Promise\<boolean\>
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result.
......@@ -427,9 +427,9 @@ promise.then((value) => {
```
### on\('open'\)
### on('open')
on\(type: 'open', callback: AsyncCallback<Object\>\): void
on(type: 'open', callback: AsyncCallback\<Object\>): void
Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -453,9 +453,9 @@ ws.on('open', (err, value) => {
```
### off\('open'\)
### off('open')
off\(type: 'open', callback?: AsyncCallback<Object\>\): void
off(type: 'open', callback?: AsyncCallback\<Object\>): void
Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -484,14 +484,14 @@ ws.off('open', callback1);
```
### on\('message'\)
### on('message')
on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void
on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void
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**
>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).
**System capability**: SystemCapability.Communication.NetStack
......@@ -512,14 +512,14 @@ ws.on('message', (err, value) => {
```
### off\('message'\)
### off('message')
off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void
off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void
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**
>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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -539,9 +539,9 @@ ws.off('message');
```
### on\('close'\)
### on('close')
on\(type: 'close', callback: AsyncCallback<\{ code: number, reason: string \}\>\): void
on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void
Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -552,7 +552,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| 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.|
**Example**
......@@ -564,9 +564,9 @@ ws.on('close', (err, value) => {
```
### off\('close'\)
### off('close')
off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\>\): void
off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void
Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -580,7 +580,7 @@ Disables listening for the **close** events of a WebSocket connection. This API
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| 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.|
**Example**
......@@ -590,9 +590,9 @@ ws.off('close');
```
### on\('error'\)
### on('error')
on\(type: 'error', callback: ErrorCallback\): void
on(type: 'error', callback: ErrorCallback): void
Enables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -615,9 +615,9 @@ ws.on('error', (err) => {
```
### off\('error'\)
### off('error')
off\(type: 'error', callback?: ErrorCallback\): void
off(type: 'error', callback?: ErrorCallback): void
Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......
......@@ -15,6 +15,7 @@ This error code is reported if the **write** API is called to perform applicatio
The application event logging function is disabled.
**Solution**
Invoke the **configure** API to enable the application event logging function.
```js
......@@ -41,6 +42,7 @@ The specified event domain name does not comply with the following rules:
- The event domain name is not empty and contains a maximum of 32 characters.
**Solution**
Specify a valid event domain name.
## 11101002 Invalid Event Name
......
......@@ -12,15 +12,13 @@ The HiTraceMeter subsystem consists of three parts:
- hitrace CLI tool for data collection
- 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.
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.
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.
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.
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
constexpr uint64_t HITRACE_TAG_NEVER = 0; // This tag is never enabled.
......@@ -73,7 +71,7 @@ constexpr uint64_t HITRACE_TAG_NOT_READY = (1ULL << 63); // Reserved for initial
constexpr uint64_t HITRACE_TAG_VALID_MASK = ((HITRACE_TAG_LAST - 1) | HITRACE_TAG_LAST);
```
## Implementation Principle
## Implementation Principles
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
## 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.
......@@ -98,7 +95,6 @@ HiTraceMeter development focuses on two parts: JS/C++ event logging APIs and the
## 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.
......@@ -109,18 +105,17 @@ Only C++ APIs are now open for system developers. If you're developing a JS app,
**Table 1** Sync APIs
| API | Function |Parameter Description |
| :----------------------------------------------------------- | ------------- |------------- |
| 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 FinishTrace(uint64_t label); | Stops a synchronous trace.|**label**: trace category.|
| Sync trace | Function | Parameter Description |
|:---------------------------------------------------------------------------- | --------- | --------------------------------------------------------------------- |
| 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 FinishTrace(uint64_t label); | Stops a synchronous trace.| **label**: trace category. |
**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
| 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 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
**Table 3** Counter APIs
| API | 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.|
| Counter Trace | Function | Parameter Description |
| ------------------------------------------------------------------ | ------- | -------------------------------------------------------------- |
| 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
1. Add the build dependencies to the build configuration file **base\hiviewdfx\hitrace\cmd\BUILD.gn**.
```
external_deps = [ "hitrace_native:hitrace_meter"]
```
2. Add the header file dependencies.
```cpp
#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
#include "hitrace_meter.h" // Include hitrace_meter.h
using namespace std;
CountTrace(label, "count number", 2000); // Integer trace
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.
```
hdc_std shell hitrace -t 10 ohos > .\myapp_demo.ftrace
```
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
using namespace std;
int main()
{
int main()
{
uint64_t label = BYTRACE_TAG_OHOS;
sleep(1);
CountTrace(label, "count number", 2000); // Integer trace
......@@ -193,11 +163,20 @@ int main()
sleep(1);
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
return 0;
}
```
```
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.
```
hdc_std shell hitrace -t 10 ohos > .\myapp_demo.ftrace
```
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
......@@ -292,10 +271,10 @@ The hitrace CLI tool is an executable binary program. On an OpenHarmony-powered
**Table 4** Command list
| Option | Description |
| ------------------------------ | ------------------------------------------------------------ |
| ----------------------------- | -------------------------------------------------------- |
| -h, --help | Views the help Information. |
| -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_begin | Starts capturing trace data. |
| --trace_dump | Dumps trace data to the specified position. The default position is the console. |
......@@ -310,34 +289,41 @@ Examples:
- Query supported labels.
```
hitrace -l
```
Or,
Alternatively, run the following command:
```
hitrace --list_categories
```
```
- Trace ability information for 10 seconds and store the trace data in a buffer of 4 MB.
```
hitrace -b 4096 -t 10 --overwrite ability > /data/log/mytrace.ftrace
```
```
- Set the clock type to **mono**.
```
hitrace --trace_clock mono -b 4096 -t 10 --overwrite ability > /data/log/mytrace.ftrace
```
```
- Compress the trace data.
```
hitrace -z -b 4096 -t 10 --overwrite ability > /data/log/mytrace.ftrace
```
......@@ -348,14 +334,18 @@ Examples:
#### Symptom
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
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).
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册