App Performance Analytics API

更新时间:
复制 MD 格式

This topic describes the APIs that App Performance Analytics supports and how to use them.

1. Report HTTP network data

Feature description

The software development kit (SDK) provides an interface that lets you report HTTP network data from your application. You can then view statistical data about these network requests in the console.

Note

The HarmonyOS platform does not have a global network listener method. Therefore, you must use the reporting interface to actively report data.

API definition

The following definitions apply:

/**
 * Reports network data.
 */
export interface INetworkEventReporter {
  /**
   * Sets the request URL.
   * @param url
   * @returns
   */
  url(url: string): INetworkEventReporter;

  /**
   * Sets the request options.
   * @param options
   * @returns
   */
  httpOptions(options: http.HttpRequestOptions): INetworkEventReporter;

  /**
   * Sets the request error.
   * @param error
   * @returns
   */
  error(error: Error): INetworkEventReporter;

  /**
   * Sets the request response.
   * @param response
   * @returns
   */
  httpResponse(response: http.HttpResponse): INetworkEventReporter;

  /**
   * Sets the business error code.
   * @param code
   * @returns
   */
  businessCode(code: string): INetworkEventReporter;

  /**
   * Sets the response header.
   * @param headers
   * @returns
   */
  responseHeader(headers: Object): INetworkEventReporter;

  /**
   * Sets the response status code.
   * @param code
   * @returns
   */
  statusCode(code: number): INetworkEventReporter;

  /**
   * Sets the RCP request.
   * @param request
   * @returns
   */
  rcpRequest(request: rcp.Request): INetworkEventReporter;

  /**
   * Sets the RCP response.
   * @param response
   * @returns
   */
  rcpResponse(response: rcp.Response): INetworkEventReporter;

  /**
   * Triggers the report.
   */
  report(): void;
}

export interface IPerformanceApi extends IPlugin {
  /**
   * Obtains a network reporting interface.
   * @returns 
   */
  networkEventReporter(): INetworkEventReporter;
}

The HarmonyOS platform provides two APIs for HTTP requests: HTTP data requests and Remote Communication Kit.

The network reporting interface provides methods for different request types. The following table describes these methods.

Configuration method

Scenario description

url(url: string)

Used for HTTP data request scenarios. Sets the request URL. This parameter is required.

httpOptions(options: http.HttpRequestOptions)

Used for HTTP data request scenarios. Sets the request parameters. This parameter is recommended.

error(error: Error)

Used for HTTP data request scenarios. Sets the error message. Configure this parameter when a request fails. This parameter is recommended.

httpResponse(response: http.HttpResponse)

Used for HTTP data request scenarios. Sets the response. This parameter is recommended.

businessCode(code: string)

Common to all scenarios. Sets the business error code. This parameter is recommended.

responseHeader(headers: Object)

Used for HTTP data request scenarios that use requestInStream. Sets the response header. This parameter is recommended.

statusCode(code: number)

Used for HTTP data request scenarios that use requestInStream. Sets the HTTP status code. This parameter is recommended.

rcpRequest(request: rcp.Request)

Used for Remote Communication Kit scenarios. Sets the request. This parameter is required.

rcpResponse(response: rcp.Response)

Used for Remote Communication Kit scenarios. Sets the response. This parameter is required.

report()

Ends the configuration and reports the current network request data.

Code examples

  • HTTP data request scenario that uses the request method to initiate a request.

        let httpRequest = http.createHttp();
        const options: http.HttpRequestOptions = {
          method: http.RequestMethod.POST,
          // Other parameter settings are omitted.
        }
        httpRequest.request(
          url, options, (err: BusinessError, data: http.HttpResponse) => {
          performanceApi.networkEventReporter()
            .url(url)
            .httpOptions(options)
            .error(err)
            .httpResponse(data)
            .report();
          if (!err) {
            // data.result is the HTTP response content. Parse it as needed.
            console.info('Result:' + JSON.stringify(data.result));
            // When the request is complete, call the destroy method to release resources.
            httpRequest.destroy();
          } else {
            console.error('error:' + JSON.stringify(err));
            // When the request is complete, call the destroy method to release resources.
            httpRequest.destroy();
          }
        });
  • HTTP data request scenario that uses the requestInStream method to initiate a request.

      const reporter = performanceApi.networkEventReporter();
      let httpRequest = http.createHttp();
      httpRequest.on("headersReceive", (header: Object) => {
        reporter.responseHeader(header);
      });
      let result: ArrayBuffer[] = [];
      httpRequest.on('dataReceive', (data)=> {
        result.push(data)
      })
      httpRequest.on("dataEnd", () => {
        console.log(`result is ${buffer.from(buffer.concat(result.map(buf=>new Uint8Array(buf)))).toString()}`)
      });
    
      const options: http.HttpRequestOptions = {
        method: http.RequestMethod.GET,
        // Other parameters are omitted.
      }
      reporter.url(url).httpOptions(options)
      httpRequest.requestInStream(
        url, options, (err: BusinessError, data: number) => {
          reporter.error(err).statusCode(data).report();
        if (!err) {
          httpRequest.off('dataReceive');
          httpRequest.off('headersReceive');
          httpRequest.off('dataEnd');
          // When the request is complete, call the destroy method to release resources.
          httpRequest.destroy();
        } else {
          httpRequest.off('dataReceive');
          httpRequest.off('headersReceive');
          httpRequest.off('dataEnd');
          httpRequest.destroy();
        }
      });
  • Remote Communication Kit scenario.

    /**
     * Obtains network data through an interceptor and reports the data.
     */
    class MyInterceptor implements rcp.Interceptor {
    
      async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
        let response: rcp.Response;
        try {
          response = await next.handle(context);
          performanceApi.networkEventReporter().rcpRequest(context.request).rcpResponse(response).report();
        } catch (e) {
          performanceApi.networkEventReporter().rcpRequest(context.request).error(e).report();
          throw e as Error;
        }
        return response;
      }
    }
    
    try {
      const request = new rcp.Request(url, "GET");
      const session = rcp.createSession({
        interceptors: [new MyInterceptor()],
        requestConfiguration: {
          tracing: {
            // Enable time consumption statistics. Otherwise, network time consumption data is not available.
            collectTimeInfo: true
          }
        }
      });
      session.fetch(request).then((rep: rcp.Response) => {
        console.info(`Response succeeded: ${rep}`);
      }).catch((err: BusinessError) => {
        console.error(`Response err: Code is ${err.code}, message is ${JSON.stringify(err)}`);
      });
    } catch (e) {
      console.error(`requestRCP fail ${JSON.stringify(e)}`)
    }