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**
>
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
...
...
@@ -18,17 +20,17 @@ import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
lethttpRequest=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+
// 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.
// 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 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'
},
...
...
@@ -48,7 +50,7 @@ httpRequest.request(
console.info('cookies:'+data.cookies);// 8+
}else{
console.info('error:'+JSON.stringify(err));
// Call the destroy() method to release resources after the call is complete.
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
}
...
...
@@ -79,7 +81,7 @@ let httpRequest = http.createHttp();
## HttpRequest
Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
### request
...
...
@@ -93,9 +95,9 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **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.
| method | [RequestMethod](#requestmethod) | No | Request method. |
| extraData | string \| Object \| ArrayBuffer<sup>8+</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>8+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> |
| 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. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| 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. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
## RequestMethod
...
...
@@ -388,13 +388,13 @@ Enumerates the response codes for an HTTP request.
| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. |
| OK | 200 | Request succeeded. 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. |
| 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. |
| NO_CONTENT | 204 | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body. |
| RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. |
| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. |
| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. |
| MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. |
| MOVED_PERM | 301 | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.|
| MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. |
...
...
@@ -418,7 +418,7 @@ Enumerates the response codes for an HTTP request.
| REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. |
| UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. |
| INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. |
| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. |
| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. |
| BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.|
| UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. |
| GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. |
...
...
@@ -433,6 +433,17 @@ Defines the response to an HTTP request.
| result | string \| Object \| ArrayBuffer<sup>8+</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|
| 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**. The error code can be one of the following:<br>- 200: common error<br>- 202: parameter error<br>- 300: I/O error|
| 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'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running, helping you locate faults. In addition, you can upload the log data to the cloud for big data analytics.
Before logging system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md).
## Development Guidelines<a name="section314416685113"></a>
### Available APIs<a name="section13480315886"></a>
The following table lists the C++ APIs provided by the HiSysEvent class.
For details about the HiSysEvent class, see the API reference.
**Table 1** C++ APIs provided by HiSysEvent
| API| Description|
| -------- | --------- |
| template<typename... Types> static int Write(const std::string &domain, const std::string &eventName, EventType type, Types... keyValues) | Logs system events. <br><br>Input arguments: <ul><li>**domain**: Indicates the domain related to the event. You can use a preconfigured domain or customize a domain as needed. The name of a custom domain can contain a maximum of 16 characters, including digits (0-9) and uppercase letters (A-Z). It must start with a letter. </li><li>**eventName**: Indicates the event name. The value contains a maximum of 32 characters, including digits (0 to 9), letters (A-Z), and underscores (_). It must start with a letter and cannot end with an underscore. </li><li>**type**: Indicates the event type. For details, see EventType. </li><li>**keyValues**: Indicates the key-value pairs of event parameters. It can be in the format of the basic data type, std::string, std::vector<basic data type>, or std:vector<std::string>. The value contains a maximum of 48 characters, including digits (0 to 9), letters (A-Z), and underscores (_). It must start with a letter and cannot end with an underscore. The number of parameter names cannot exceed 32. </li></ul>Return value: <ul><li>**0**: The logging is successful. </li><li>Negative value: The logging has failed.</li></ul> |
**Table 2** Description of HiSysEvent::Domain APIs
| static const std::string WEARABLE_HARDWARE | Wearable-dedicated service subsystem|
| static const std::string OTHERS | Others|
**Table 3** Description of HiSysEvent::EventType
| Name| Description|
| -------- | --------- |
| FAULT | Fault event|
# HiSysEvent Logging
## Overview
### Introduction
HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running. Besides, it supports shielding of event logging by event domain, helping you to evaluate the impact of event logging.
### Working Principles
Before logging system events, you need to complete HiSysEvent logging configuration. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md).
## Development Guidelines
### When to Use
Use HiSysEvent logging to flush logged event data to disks.
### Available APIs
#### C++ Event Logging APIs
HiSysEvent logging is implemented using the API provided by the **HiSysEvent** class. For details, see the API Reference.
> In OpenHarmony-3.2-Beta3, HiSysEvent logging is open for restricted use to avoid event storms. The **HiSysEvent::Write** API in Table 1 is replaced by the **HiSysEventWrite** API in Table 2. The **HiSysEvent::Write** API has been deprecated. Use the **HiSysEventWrite** API instead for HiSysEvent logging.
| template<typename... Types> <br>static int Write(const std::string &domain, const std::string &eventName, EventType type, Types... keyValues) | Flushes logged event data to disks.|
| int hisysevent_put_integer(struct hiview_hisysevent *event, const char *key, long long value); | Adds event parameters of the integer type to a **hisysevent** object. |
| int hisysevent_put_string(struct hiview_hisysevent *event, const char *key, const char *value); | Adds event parameters of the string type to a **hisysevent** object.|
| int hisysevent_write(struct hiview_hisysevent *event); | Flushes **hisysevent** object data to disks. |
Table 5 Kernel event types
| Event | Description |
| --------- | ------------ |
| FAULT | Fault event|
| STATISTIC | Statistical event|
| SECURITY | Security event|
| BEHAVIOR | System behavior event|
| SECURITY | Security event|
| BEHAVIOR | Behavior event|
### How to Develop
#### C++ Event Logging
1. Call the event logging API wherever needed, with required event parameters passed to the API.
2. Pass the customized event parameters to the **hisysevent** object.
### Development Example<a name="section112771171317"></a>
```c
// Add a parameter of the integer type.
hisysevent_put_integer(event,"BOOT_TIME",100);
C++
// Add a parameter of the string type.
hisysevent_put_string(event,"MSG","This is a test message");
```
1. Develop the source code.
3. Trigger reporting of the **hisysevent** event.
Include the HiSysEvent header file in the class definition header file or class implementation source file. For example:
```c
hisysevent_write(event);
```
4. Manually destroy the **hisysevent** object.
```c
hisysevent_destroy(&event);
```
#### Shielding of Event Logging by Event Domain
1. In the corresponding file, define the **DOMAIN_MASKS** macro with content similar to DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n. There are three scenarios:
- Shielding only event logging for the event domains configured in the current source code file: Define the **DOMAIN_MASKS** macro before importing the **.cpp** file to the **hisysevent.h** file.
HiSysEventWrite(domain,eventName,eventType);// Event logging is shielded for DOMAIN_NAME_1 because it has been defined in the DOMAIN_MASKS macro.
```
### Development Examples
#### C++ Event Logging
Assume that a service module needs to trigger event logging during application startup to record the application startup event and application bundle name. The following is the complete sample code:
1. Add the HiSysEvent component dependency to the **BUILD.gn** file of the service module.
```c++
external_deps=["hisysevent_native:libhisysevent"]
```
2. In the application startup function **StartAbility()** of the service module, call the event logging API with the event parameters passed in.
Assume that the kernel service module needs to trigger event logging during device startup to record the device startup event. The following is the complete sample code:
1. In the device startup function **device_boot()**, construct a **hisysevent** object. After that, trigger event reporting, and then destroy the **hisysevent** object.
ret = hisysevent_put_string(event, "MSG", "This is a test message");
if (ret != 0) {
pr_err("failed to put sting to event, ret=%d", ret);
goto hisysevent_end;
}
ret = hisysevent_write(event);
hisysevent_end:
hisysevent_destroy(&event);
... // Other service logic
}
```
#### Shielding of Event Logging by Event Domain
- If you want to shield event logging for the **AAFWK** and **POWER** domains in a **.cpp** file, define the **DOMAIN_MASKS** macro before including the **hisysevent.h** header file to the **.cpp** file.
```c++
#define DOMAIN_MASKS "AAFWK|POWER"
#include "hisysevent.h"
```
...// Other service logic
HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::AAFWK,"JS_ERROR",OHOS:HiviewDFX::HiSysEvent::EventType::FAULT,"MODULE","com.ohos.module");// HiSysEvent logging is not performed.
...// Other service logic
HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::POWER,"POWER_RUNNINGLOCK",OHOS:HiviewDFX::HiSysEvent::EventType::FAULT,"NAME","com.ohos.module");// HiSysEvent logging is not performed.
Add the event logging code. For example, if you want to log events specific to the app start time (start\_app), then add the following code to the service implementation source file:
```
- If you want to shield event logging for the **AAFWK** and **POWER** domains of the entire service module, define the **DOMAIN_MASKS** macro as follows in the **BUILG.gn** file of the service module.
- If you want to shield event logging for the **AAFWK** and **POWER** domains globally, define the **DOMAIN_MASKS** macro as follows in **/build/config/compiler/BUILD.gn**.
```gn
... // Other configuration items
cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""]
```
2. Configure compilation information. Specifically, add the subsystem SDK dependency to **BUILD.gn**.
The HiSysEvent module writes the logged event data to the node file, and the Hiview module parses and processes the event data in a unified manner. For details, see the [Hiview Development Guide](subsys-dfx-hiview.md).
HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running, helping you locate faults. In addition, you can upload the log data to the cloud for big data analytics.
The key modules of HiSysEvent are described as follows:
- Event configuration: enables you to define HiSysEvent events in YAML files.
- Trace point configuration: provides trace point APIs and supports flushing of HiSysEvent events to disks.
- Event subscription: provides APIs for you to subscribe to HiSysEvent events by event domain and event name.
- Event query: provides APIs for you to query HiSysEvent events by event domain and event name.
- Event debugging tool: allows you to subscribe to real-time HiSysEvent events and query historical HiSysEvent events.
## Reference
For more information about the source code and usage of HiSysEvent, access the HiSysEvent code repository(https://gitee.com/openharmony/hiviewdfx_hisysevent).
Hiview is a module that provides toolkits for device maintenance across different platforms. It consists of the plugin management platform and the service plugins running on the platform. Hiview works in event-driven mode. The core of Hiview is a collection of HiSysEvent stubs distributed in the system. Formatted events are reported to Hiview through the HiSysEvent API for processing. The following figure shows the data interaction process.
**Figure 1** Data interaction between Hiview modules
1. The service process calls the event logging API to report logged event information and writes the information to the node file.
2. SysEventSource of the Hiview process asynchronously reads event information from the node file and distributes the event to SysEventPipeline for processing.
- The SysEventService plugin verifies events and flushes them to disks.
- The Faultlogger plugin processes fault-related events.
- The EventLogger plugin collects event-related log information.
3. On completion of event processing, SysEventPipeline sends the events to the event subscription queue and then dispatches the events to the subscription plugin for processing.
Before you get started, familiarize yourself with the following concepts:
- Plug-in
An independent module running in the Hiview process. A plugin is delivered with the Hiview binary file to implement maintenance and fault management functions independently. Plug-ins can be disassembled independently during compilation, and can be hosted on the platform during running and dynamically configured.
- Pipeline
An ordered set of event processing plugins. Events entering the pipeline are processed by plugins on the pipeline in sequence.
- Event source
A special plugin that can produce events. Different from common plugins, a special plugin can be bound to a pipeline, and can produce events and distribute them to the pipeline.
- Pipeline group
A group of pipelines configured on the same event source.
### Working Principles
Hiview supports plugin development on the plugin management platform and provides the required plugin development capabilities. You can add plugins to the Hiview platform to implement HiSysEvent event processing. Before you get started, you're expected to have a basic understanding of plugin working principles.
#### Plug-in Registration
A plugin can be registered in any of the following modes.
| Static registration | Use the **REGISTER(xxx);** macro to register the plugin. Such a plugin cannot be unloaded.|
| Proxy registration | Use the **REGISTER_PROXY(xxx);** macro to register the plugin. Such a plugin is not loaded upon startup and can be loaded and unloaded dynamically during system running.|
| Proxy registration and loading upon startup| Use the **REGISTER_PROXY_WITH_LOADED(xxx);** macro to register the plugin. Such a plugin is loaded upon startup and can be unloaded and loaded dynamically during system running.|
#### Plug-in Event-Driven Modes
There are two event-driven modes available for plugins: pipeline-driven and subscription-driven. The differences are as follows:
- Pipeline-driven plugins need to be configured on the pipeline. After an event is distributed from an event source to the pipeline, the event traverses the plugins configured on the pipeline in sequence for processing.
- Subscription-driven plugins do not need to be configured on the pipeline. However, a listener needs to be registered with the Hiview platform upon plugin startup, and the plugin needs to implement the event listener function.
#### Plug-in Loading
Depending on your service demand, you can compile all or some plugins into the Hiview binary file.
Multiple plugins can be built into an independent plugin package and preset in the system as an independent **.so** file. One **.so** file corresponds to one **plugin_config** file. For example, **libxxx.z.so** corresponds to the** xxx_plugin_config** file. When the Hiview process starts, it scans for the plugin package (**.so** file) and the corresponding configuration file and loads the plugins in the plugin package.
The plugin package is described as follows:
1. The plugin package runs on the plugin management platform as an independent entity. The plugins, pipelines, or event sources in it provide the same functions as the plugins in the Hiview binary.
2. Plug-ins in the plugin package can be inserted into the Hiview binary pipeline.
3. Subscribers, wherever they are located, can receive events sent by the platform based on the subscription rules.
## Plug-in Development Guide
### When to Use
You can deploy a plugin on the Hiview platform if you want to perform specific service processing on the HiSysEvent events distributed from the event source. The following table describes the APIs used for plugin development.
### Available APIs
The following table lists the APIs related to plugin development. For details about the APIs, see the API Reference.
| virtual void OnLoad() | Loads plugins. After plugins are loaded, you can call this API to initialize data.|
| virtual void OnUnload() | Unloads plugins. Before plugins are unloaded, you can call this API to reclaim data. |
| virtual bool ReadyToLoad() | Checks whether the current plugin can be loaded when the Hiview starts plugin loading. |
| virtual bool OnEvent(std::shared_ptr\<Event\>& event) | Implements event processing. You can call this API to receive events distributed by the pipeline or platform perform service processing.|
| virtual bool CanProcessEvent(std::shared_ptr\<Event\> event) | Checks whether an event can traverse backward throughout the entire pipeline. This function takes effect only when the plugin is the first one in the pipeline.|
| HiviewContext* GetHiviewContext() | Obtains the context of the Hiview plugin management platform. |