未验证 提交 7cadc96e 编写于 作者: O openharmony_ci 提交者: Gitee

!13223 翻译已完成12598+12570+12443+12334+12307+12295+12283

Merge pull request !13223 from shawn_he/12283-a
# DFX # DFX
- Application Event Logging - [Development of Application Event Logging](hiappevent-guidelines.md)
- [Overview of Application Event Logging](hiappevent-overview.md) - [Development of Performance Tracing](hitracemeter-guidelines.md)
- [Development of Application Event Logging](hiappevent-guidelines.md) - [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- Performance Tracing
- [Overview of Performance Tracing](hitracemeter-overview.md)
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- Distributed Call Chain Tracing
- [Overview of Distributed Call Chain Tracing](hitracechain-overview.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- Error Management - Error Management
- [Development of Error Manager](errormanager-guidelines.md) - [Development of Error Manager](errormanager-guidelines.md)
- [Development of Application Recovery](apprecovery-guidelines.md)
# Development of Application Recovery
## When to Use
During application running, some unexpected behaviors are inevitable. For example, unprocessed exceptions and errors are thrown, and the call or running constraints of the framework are violated.
By default, the processes will exit as exception handling. However, if user data is generated during application use, process exits may interrupt user operations and cause data loss.
In this way, application recovery APIs may help you save temporary data, restart an application after it exits, and restore its status and data, which deliver a better user experience.
Currently, the APIs support only the development of an application that adopts the stage model, single process, and single ability.
## Available APIs
The application recovery APIs are provided by the **appRecovery** module, which can be imported via **import**. For details, please refer to [Development Example](#development-example). This document describes behaviors of APIs in API version 9, and the content will update with changes.
### Available APIs
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; | Enables the application recovery function. |
| saveAppState(): boolean; | Saves the ability status of an application. |
| restartApp(): void; | Restarts the current process. If there is saved ability status, it will be passed to the **want** parameter's **wantParam** attribute of the **onCreate** lifecycle callback of the ability.|
The APIs are used for troubleshooting and do not return any exception. Therefore, you need to be familiar with when they are used.
**enableAppRecovery**: This API should be called during application initialization. For example, you can call this API in **onCreate** of **AbilityStage**. For details, please refer to the [parameter description](../reference/apis/js-apis-app-ability-appRecovery.md).
**saveAppState**: After this API is called, the framework calls back **onSaveState** of the ability. If data saving is agreed to in this method, relevant data and the page stack of the ability are persisted to the local cache of the application.
**restartApp**: After this API is called, the framework kills the current application process and restarts the ability in the foreground, with **APP_RECOVERY** specified as the startup cause.
### Framework Fault Management Process
Fault management is an important way for applications to deliver a better user experience. The application framework offers three methods for application fault management: fault listening, fault rectification, and fault query.
- Fault listening refers to the process of registering [ErrorObserver](../reference/apis/js-apis-application-errorManager.md#errorobserver) via [errorManager](../reference/apis/js-apis-application-errorManager.md), listening for fault occurrence, and notifying the fault listener.
- Fault rectification refers to [appRecovery](../reference/apis/js-apis-app-ability-appRecovery.md) and restarts an application to restore its status previous to a fault.
- Fault query indicates that [faultLogger](../reference/apis/js-apis-faultLogger.md) obtains the fault information using its query API.
The figure below does not illustrate the time when [faultLogger](../reference/apis/js-apis-faultLogger.md) is called. You can refer to [LastExitReason](../reference/apis/js-apis-application-abilityConstant.md#abilityconstantlastexitreason) passed during application initialization to determine whether to call [faultLogger](../reference/apis/js-apis-faultLogger.md) to query the information about the last fault.
![Fault rectification process](./figures/fault_rectification.png)
It is recommended that you call [errorManager](../reference/apis/js-apis-application-errorManager.md) to process the exception. After the processing is complete, you can call the status saving API and restart the application.
If you do not register [ErrorObserver](../reference/apis/js-apis-application-errorManager.md#errorobserver) or enable application recovery, the application process will exit according to the default processing logic of the system. Users can restart the application from the home screen.
If you have enabled application recovery, the framework first checks whether a fault allows for ability status saving and whether you have configured ability status saving. If so, [onSaveState](../reference/apis/js-apis-application-ability.md#abilityonsavestate) of [Ability](../reference/apis/js-apis-application-ability.md#ability) is called back. Finally, the application is restarted.
### Scenarios Supported by Application Fault Management APIs
Common fault types include JavaScript application crash, application freezing, and C++ application crash. Generally, an application is closed when a crash occurs. Application freezing occurs when the application does not respond. The fault type can be ignored for the upper layer of an application. The recovery framework implements fault management in different scenarios based on the fault type.
| Fault | Fault Listening| Status Saving| Automatic Restart| Log Query|
| ------------------------------------------------------------ | -------- | -------- | -------- | -------- |
| [JS_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | Supported | Supported | Supported | Supported |
| [APP_FREEZE](../reference/apis/js-apis-faultLogger.md#faulttype) | Not supported | Not supported | Supported | Supported |
| [CPP_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | Not supported | Not supported | Not supported | Supported |
**Status Saving** in the table header means status saving when a fault occurs. To protect user data as much as possible in the application freezing fault, you can adopt either the periodic or automatic way, and the latter will save user data when an ability is switched to the background.
## Development Example
### Enabling Application Recovery
Enable **appRecovery** during application initialization. The following is an example of **AbilityStage**:
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage'
import appRecovery from '@ohos.app.ability.appRecovery'
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.info("[Demo] MyAbilityStage onCreate")
appRecovery.enableAppRecovery(appRecovery.RestartFlag.ALWAYS_RESTART,
appRecovery.SaveOccasionFlag.SAVE_WHEN_ERROR | appRecovery.SaveOccasionFlag.SAVE_WHEN_BACKGROUND,
appRecovery.SaveModeFlag.SAVE_WITH_FILE);
}
}
```
### Saving and Restoring Data
After enabling **appRecovery**, you can use this function by either actively or passively saving the status and restoring data in the ability.
The following is an example of **MainAbility**:
#### Importing the Service Package
```ts
import errorManager from '@ohos.app.ability.errorManager'
import appRecovery from '@ohos.app.ability.appRecovery'
import AbilityConstant from '@ohos.app.ability.AbilityConstant'
```
#### Actively Saving Status and Restoring Data
- Define and register the [ErrorObserver](../reference/apis/js-apis-application-errorManager.md#errorobserver) callback.
```ts
var registerId = -1;
var callback = {
onUnhandledException: function (errMsg) {
console.log(errMsg);
appRecovery.saveAppState();
appRecovery.restartApp();
}
}
onWindowStageCreate(windowStage) {
// Main window is created. Set a main page for this ability.
console.log("[Demo] MainAbility onWindowStageCreate")
globalThis.registerObserver = (() => {
registerId = errorManager.registerErrorObserver(callback);
})
windowStage.loadContent("pages/index", null);
}
```
- Save data.
After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state, wantParams)** of **MainAbility** is triggered.
```ts
onSaveState(state, wantParams) {
// Save application data.
console.log("[Demo] MainAbility onSaveState")
wantParams["myData"] = "my1234567";
return AbilityConstant.onSaveResult.ALL_AGREE;
}
```
- Restore data.
After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onSaveState(state, wantParams)** of **MainAbility** is called, and the saved data is in **parameters** of **want**.
```ts
storage: LocalStorage
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage();
let recoveryData = want.parameters["myData"];
this.storage.setOrCreate("myData", recoveryData);
this.context.restoreWindowStage(this.storage);
}
}
```
- Deregister **ErrorObserver callback**.
```ts
onWindowStageDestroy() {
// Main window is destroyed to release UI resources.
console.log("[Demo] MainAbility onWindowStageDestroy")
globalThis.unRegisterObserver = (() => {
errorManager.unregisterErrorObserver(registerId, (result) => {
console.log("[Demo] result " + result.code + ";" + result.message)
});
})
}
```
#### Passively Saving Status and Restoring Data
This is triggered by the recovery framework. You do not need to register **ErrorObserver callback**. You only need to implement **onSaveState** of the ability for status saving and **onCreate** of the ability for data restoration.
```ts
export default class MainAbility extends Ability {
storage: LocalStorage
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage();
let recoveryData = want.parameters["myData"];
this.storage.setOrCreate("myData", recoveryData);
this.context.restoreWindowStage(this.storage);
}
}
onSaveState(state, wantParams) {
// Save application data.
console.log("[Demo] MainAbility onSaveState")
wantParams["myData"] = "my1234567";
return AbilityConstant.onSaveResult.ALL_AGREE;
}
}
```
# Development of Application Event Logging # Development of Application Event Logging
## When to Use ## Introduction
The event logging function helps applications log various information generated during running. A traditional log system aggregates log information generated by all application processes running on the entire device, making it difficult to identify key information in the logs. Therefore, an effective logging mechanism is needed to evaluate mission-critical information, for example, number of visits, number of daily active users, user operation habits, and key factors that affect application usage.
HiAppEvent is a module that provides the event logging function for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of applications.
## Basic Concepts
**Logging**
A function that logs changes caused by user operations to provide service data for development, product, and O&M analysis.
## Event Design Specifications
- Event domain: identifies the domain of an event. You are advised to set this parameter to the service module name to differentiate service modules.
- Event name: specifies the name of an event. You are advised to set this parameter to a specific service name to differentiate services.
- Event type: specifies the type of an event. Four event types are supported:
- Behavior event: used to record the daily operation behavior of a user, for example, button clicking and page redirection.
- Fault event: used to locate and analyze application faults, for example, frame freezing, network disconnection, and call drop.
- Statistical event: used to collect statistics on key application behaviors, for example, usage duration and number of visits.
- Security event: used to record events related to application security, for example, password change and user authorization.
- Event parameter: specifies the parameters of an event. Each event can contain a group of parameters. You are advised to set this parameter to an event attribute or event context to depict the event details.
## Available APIs ## Available APIs
......
# Overview of Application Event Logging
HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application.
The HiAppEvent module can be used to develop application event-related functions, including flushing application events to a disk and querying historical application events.
## Basic Concepts
**Logging**
A function that logs changes caused by user operations to provide service data for development, product, and O&M analysis.
\ No newline at end of file
# Development of Distributed Call Chain Tracing # Development of Distributed Call Chain Tracing
## When to Use ## Introduction
HiTraceChain is the module that provides APIs to implement call chain tracing throughout a service process. With HiTraceChain, you can quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications. The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications.
hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing. It allows applications to trace cross-thread, cross-process, and cross-device service calls. The hiTraceChain module generates a unique **chainId** for a service process and passes it to various information (including application events, system time, and logs) specific to the service process. During debugging and fault locating, you can use the unique **chainId** to quickly correlate various information related to the service process.
## Basic Concepts
- **chainId**
Distributed call chain tracing ID, which is a part of **HiTraceId** and is used to identify the service process being traced.
## Available APIs ## Available APIs
......
# Overview of Distributed Call Chain Tracing
hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing. It allows applications to trace cross-thread, cross-process, and cross-device service calls.
## Basic Concepts
- **chainId**
Distributed call chain tracing ID, which is a part of **HiTraceId** and is used to identify the service process being traced.
## Working Principles
The hiTraceChain module generates a unique **chainId** for a service process and passes it to various information (including application events, system time, and logs) specific to the service process. During debugging and fault locating, you can use the unique **chainId** to quickly correlate various information related to the service process.
## Constraints
All APIs provided by the hiTraceChain module work in synchronous mode.
# Development of Performance Tracing # Development of Performance Tracing
## When to Use ## Introduction
HiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by HiTraceMeter module in your own service logic to effectively track service processes and check the system performance. hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance.
## Basic Concepts
- **hiTraceMeter Tag**
Tag used for tracing data categorization. It is also known as **hiTraceMeter Category**. Generally, one subsystem maps to a tag. The tag is passed as the **Tag** parameter in performance tracing APIs. When you use the hiTraceMeter CLI tool to collect tracing data, only the tracing data specified by the **Tag** parameter is collected.
## Working Principles
- The application calls hiTraceMeter APIs to perform performance tracing. The APIs output the tracing data to the kernel's ftrace data buffer through the kernel's sysfs file interface.
- The hiTraceMeter CLI tool reads the tracing data in the ftrace data buffer and saves the trace data as a text file on the device.
## Constraints
Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs.
## Available APIs ## Available APIs
......
# Overview of Performance Tracing
hiTraceMeter is a tool for you to trace service processes and monitor system performance. Through encapsulating and extending the ftrace inside the kernel, hiTraceMeter supports performance tracing for code execution in the user space. You can use hiTraceMeter APIs to implement performance tracing and use the hiTraceMeter CLI tool to collect traced data.
## Basic Concepts
- **hiTraceMeter Tag**
Tag used for tracing data categorization. It is also known as **hiTraceMeter Category**. Generally, one subsystem maps to a tag. The tag is passed as the **Tag** parameter in performance tracing APIs. When you use the hiTraceMeter CLI tool to collect tracing data, only the tracing data specified by the **Tag** parameter is collected.
## Working Principles
- The application calls hiTraceMeter APIs to perform performance tracing. The APIs output the tracing data to the kernel's ftrace data buffer through the kernel's sysfs file interface.
- The hiTraceMeter CLI tool reads the tracing data in the ftrace data buffer and saves the trace data as a text file on the device.
## Constraints
Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs.
...@@ -83,6 +83,7 @@ You can create resource group subdirectories (including element, media, and prof ...@@ -83,6 +83,7 @@ You can create resource group subdirectories (including element, media, and prof
| ------- | ---------------------------------------- | ---------------------------------------- | | ------- | ---------------------------------------- | ---------------------------------------- |
| element | Indicates element resources. Each type of data is represented by a JSON file. The options are as follows:<br>- **boolean**: boolean data<br>- **color**: color data<br>- **float**: floating-point data<br>- **intarray**: array of integers<br>- **integer**: integer data<br>- **pattern**: pattern data<br>- **plural**: plural form data<br>- **strarray**: array of strings<br>- **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type:<br>- boolean.json<br>- color.json<br>- float.json<br>- intarray.json<br>- integer.json<br>- pattern.json<br>- plural.json<br>- strarray.json<br>- string.json | | element | Indicates element resources. Each type of data is represented by a JSON file. The options are as follows:<br>- **boolean**: boolean data<br>- **color**: color data<br>- **float**: floating-point data<br>- **intarray**: array of integers<br>- **integer**: integer data<br>- **pattern**: pattern data<br>- **plural**: plural form data<br>- **strarray**: array of strings<br>- **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type:<br>- boolean.json<br>- color.json<br>- float.json<br>- intarray.json<br>- integer.json<br>- pattern.json<br>- plural.json<br>- strarray.json<br>- string.json |
| media | Indicates media resources, including non-text files such as images, audios, and videos. | The file name can be customized, for example, **icon.png**. | | media | Indicates media resources, including non-text files such as images, audios, and videos. | The file name can be customized, for example, **icon.png**. |
| profile | Indicates a user-defined configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. | The file name can be customized, for example, **test_profile.json**.|
| rawfile | Indicates other types of files, which are stored in their raw formats after the application is built as an HAP file. They will not be integrated into the **resources.index** file.| The file name can be customized. | | rawfile | Indicates other types of files, which are stored in their raw formats after the application is built as an HAP file. They will not be integrated into the **resources.index** file.| The file name can be customized. |
**Media Resource Types** **Media Resource Types**
...@@ -284,4 +285,3 @@ Image($r('sys.media.ohos_app_icon')) ...@@ -284,4 +285,3 @@ Image($r('sys.media.ohos_app_icon'))
.height(200) .height(200)
.width(300) .width(300)
``` ```
...@@ -18,9 +18,9 @@ import http from '@ohos.net.http'; ...@@ -18,9 +18,9 @@ import http from '@ohos.net.http';
```js ```js
import http from '@ohos.net.http'; 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(); let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than httpRequest. Whether to subscribe to the HTTP response header is up to your decision. // 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. // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
...@@ -38,14 +38,18 @@ httpRequest.request( ...@@ -38,14 +38,18 @@ 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.
}, (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.
console.info('Result:' + data.result); console.info('Result:' + data.result);
console.info('code:' + data.responseCode); console.info('code:' + data.responseCode);
// data.header contains the HTTP response header. Parse the content based on service requirements. // data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header)); console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + data.cookies); // 8+
} else { } else {
...@@ -78,10 +82,9 @@ import http from '@ohos.net.http'; ...@@ -78,10 +82,9 @@ import http from '@ohos.net.http';
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
``` ```
## HttpRequest ## HttpRequest
HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
### request ### request
...@@ -89,7 +92,7 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void ...@@ -89,7 +92,7 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -121,7 +124,7 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpR ...@@ -121,7 +124,7 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpR
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -158,14 +161,13 @@ httpRequest.request("EXAMPLE_URL", ...@@ -158,14 +161,13 @@ httpRequest.request("EXAMPLE_URL",
}); });
``` ```
### request ### request
request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\> request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>
Initiates an HTTP request 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.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -174,7 +176,7 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the ...@@ -174,7 +176,7 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------ | ---- | ----------------------------------------------- | | ------- | ------------------ | ---- | ----------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. | | url | string | Yes | URL for initiating an HTTP request. |
| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| | options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
**Return value** **Return value**
...@@ -226,7 +228,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void ...@@ -226,7 +228,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
Registers an observer for HTTP Response Header events. Registers an observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >**NOTE**
>This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead. >This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -250,14 +252,13 @@ httpRequest.on('headerReceive', (err, data) => { ...@@ -250,14 +252,13 @@ httpRequest.on('headerReceive', (err, data) => {
}); });
``` ```
### off\('headerReceive'\) ### off\('headerReceive'\)
off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >**NOTE**
> >
>1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead. >1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead.
> >
...@@ -301,14 +302,13 @@ httpRequest.on('headersReceive', (header) => { ...@@ -301,14 +302,13 @@ httpRequest.on('headersReceive', (header) => {
}); });
``` ```
### off\('headersReceive'\)<sup>8+</sup> ### off\('headersReceive'\)<sup>8+</sup>
off\(type: 'headersReceive', callback?: Callback<Object\>\): void off\(type: 'headersReceive', callback?: Callback<Object\>\): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -358,10 +358,14 @@ Specifies the type and value range of the optional parameters in the HTTP reques ...@@ -358,10 +358,14 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. | | method | [RequestMethod](#requestmethod) | No | Request method. |
| extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>6+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> | | extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>6+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the return data. If this parameter is set, the system returns the specified type of data preferentially.|
| usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. |
| priority<sup>9+</sup> | number | No | Priority. The value range is \[1,1000]. The default value is **1**. |
| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. |
## RequestMethod ## RequestMethod
...@@ -371,14 +375,14 @@ Defines an HTTP request method. ...@@ -371,14 +375,14 @@ Defines an HTTP request method.
| Name | Value | Description | | Name | Value | Description |
| :------ | ------- | :------------------ | | :------ | ------- | :------------------ |
| OPTIONS | OPTIONS | OPTIONS method.| | OPTIONS | "OPTIONS" | OPTIONS method.|
| GET | GET | GET method. | | GET | "GET" | GET method. |
| HEAD | HEAD | HEAD method. | | HEAD | "HEAD" | HEAD method. |
| POST | POST | POST method. | | POST | "POST" | POST method. |
| PUT | PUT | PUT method. | | PUT | "PUT" | PUT method. |
| DELETE | DELETE | DELETE method. | | DELETE | "DELETE" | DELETE method. |
| TRACE | TRACE | TRACE method. | | TRACE | "TRACE" | TRACE method. |
| CONNECT | CONNECT | CONNECT method.| | CONNECT | "CONNECT" | CONNECT method.|
## ResponseCode ## ResponseCode
...@@ -388,7 +392,7 @@ Enumerates the response codes for an HTTP request. ...@@ -388,7 +392,7 @@ Enumerates the response codes for an HTTP request.
| Name | Value | Description | | Name | Value | Description |
| ----------------- | ---- | ------------------------------------------------------------ | | ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | Request succeeded. 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. | | 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. | | 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. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
...@@ -433,17 +437,171 @@ Defines the response to an HTTP request. ...@@ -433,17 +437,171 @@ Defines the response to an HTTP request.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string| | result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. |
| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. | | cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
## http.createHttpResponseCache<sup>9+</sup>
createHttpResponseCache(cacheSize?: number): HttpResponseCache
Creates a default object to store responses to HTTP access requests.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| cacheSize | number | No| Cache size. The maximum value is 10\*1024\*1024 (10 MB). By default, the maximum value is used.|
**Return value**
| Type | Description |
| :---------- | :----------------------------------------------------------- |
| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.|
**Example**
```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
```
## HttpResponseCache<sup>9+</sup>
Defines an object that stores the response to an HTTP request.
### flush<sup>9+</sup>
flush(callback: AsyncCallback\<void>): void
Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
httpResponseCache.flush(err => {
if (err) {
console.log('flush fail');
return;
}
console.log('flush success');
});
```
### flush<sup>9+</sup>
flush(): Promise\<void>
Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void>> | Promise used to return the result.|
**Example**
```js
httpResponseCache.flush().then(() => {
console.log('flush success');
}).catch(err => {
console.log('flush fail');
});
```
### delete<sup>9+</sup>
delete(callback: AsyncCallback\<void>): void
Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
httpResponseCache.delete(err => {
if (err) {
console.log('delete fail');
return;
}
console.log('delete success');
});
```
### delete<sup>9+</sup>
delete(): Promise\<void>
Disables the cache and deletes the data in it. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
httpResponseCache.delete().then(() => {
console.log('delete success');
}).catch(err => {
console.log('delete fail');
});
```
## Error Codes ## Error Codes
| Error Code| Description | | Error Code| Description |
| ------ | ------------------------------------------------------------ | | ------ | ------------------------------------------------------------ |
| -1 | Incorrect parameters. | | -1 | Incorrect parameter. Check whether the number and type of parameters are correct. |
| 3 | Incorrect URL format. | | 3 | Incorrect URL format. Check whether the format and syntax of the URL are correct. |
| 4 | Built-in request function, protocol, or option not found during build. | | 4 | Built-in request function, protocol, or option not found during build. If a function or option is not enabled or explicitly disabled, you need to rebuild a libcurl in order to access its functions. |
| 5 | Unable to resolve the proxy. | | 5 | Unable to resolve the proxy because of a failure to resolve the specified proxy server. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 6 | Unable to resolve the host. | | 6 | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 7 | Unable to connect to the proxy or host. | | 7 | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host. |
## HttpDataType<sup>9+</sup>
Enumerates HTTP data types.
**System capability**: SystemCapability.Communication.NetStack
| Name| Value| Description |
| ------------------ | -- | ----------- |
| STRING | 0 | String type.|
| OBJECT | 1 | Object type. |
| ARRAY_BUFFER | 2 | Binary array type.|
## HttpProtocol<sup>9+</sup>
Enumerates HTTP protocol versions.
**System capability**: SystemCapability.Communication.NetStack
| Name | Description |
| :-------- | :----------- |
| HTTP1_1 | HTTP1.1 |
| HTTP2 | HTTP2 |
...@@ -33,7 +33,7 @@ Obtains the IDs of all input devices. This API uses an asynchronous callback to ...@@ -33,7 +33,7 @@ Obtains the IDs of all input devices. This API uses an asynchronous callback to
```js ```js
try { try {
inputDevice.getDeviceList((error, ids) => { inputDevice.getDeviceIds((error, ids) => {
if (error) { if (error) {
console.log(`Failed to get device list. console.log(`Failed to get device list.
error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`);
...@@ -65,7 +65,7 @@ Obtains the IDs of all input devices. This API uses a promise to return the resu ...@@ -65,7 +65,7 @@ Obtains the IDs of all input devices. This API uses a promise to return the resu
```js ```js
try { try {
inputDevice.getDeviceList().then((ids) => { inputDevice.getDeviceIds().then((ids) => {
console.log("The device ID list is: " + ids); console.log("The device ID list is: " + ids);
}); });
} catch (error) { } catch (error) {
...@@ -295,7 +295,7 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. ...@@ -295,7 +295,7 @@ This API is deprecated since API version 9. You are advised to use [inputDevice.
```js ```js
// Obtain the name of the device whose ID is 1. // Obtain the name of the device whose ID is 1.
inputDevice.getDevice(1, (inputDevice)=>{ inputDevice.getDevice(1, (error, deviceData) => {
console.log("The device name is: " + inputDevice.name); console.log("The device name is: " + inputDevice.name);
}); });
``` ```
...@@ -326,7 +326,7 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. ...@@ -326,7 +326,7 @@ This API is deprecated since API version 9. You are advised to use [inputDevice.
```js ```js
// Obtain the name of the device whose ID is 1. // Obtain the name of the device whose ID is 1.
inputDevice.getDevice(1).then((inputDevice)=>{ inputDevice.getDevice(1).then((deviceData) => {
console.log("The device name is: " + inputDevice.name); console.log("The device name is: " + inputDevice.name);
}); });
``` ```
......
...@@ -16,7 +16,7 @@ import resourceManager from '@ohos.resourceManager'; ...@@ -16,7 +16,7 @@ import resourceManager from '@ohos.resourceManager';
## Instruction ## Instruction
Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model.
For details about how to reference **context** in the stage model, see [Context in the Stage Model](../../ability/context-userguide.md). For details about how to reference **context** in the stage model, see [Context in the Stage Model](../../ability-deprecated/context-userguide.md).
```ts ```ts
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
......
...@@ -246,10 +246,8 @@ ...@@ -246,10 +246,8 @@
- [Overview of Application Event Logging](dfx/hiappevent-overview.md) - [Overview of Application Event Logging](dfx/hiappevent-overview.md)
- [Development of Application Event Logging](dfx/hiappevent-guidelines.md) - [Development of Application Event Logging](dfx/hiappevent-guidelines.md)
- Performance Tracing - Performance Tracing
- [Overview of Performance Tracing](dfx/hitracemeter-overview.md)
- [Development of Performance Tracing](dfx/hitracemeter-guidelines.md) - [Development of Performance Tracing](dfx/hitracemeter-guidelines.md)
- Distributed Call Chain Tracing - Distributed Call Chain Tracing
- [Overview of Distributed Call Chain Tracing](dfx/hitracechain-overview.md)
- [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md) - [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md)
- Error Management - Error Management
- [Development of Error Manager](dfx/errormanager-guidelines.md) - [Development of Error Manager](dfx/errormanager-guidelines.md)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册