目录

Sending a Network Request (ArkTS)

Constraints

The network request sending capability supports phones, 2-in-1 devices, tablets, and wearables. Starting from version 5.1.1(19), it is also supported on TVs.

Sending a Network Request Using FETCH

Your app can send an HTTP request, where you can set information such as the request header and request body, and obtain an HTTP response from the server. In the process, the called API returns the result asynchronously through a promise. This capability is used to obtain resources and supports stream processing and interceptor-based request and response processing.

[h2]API Description

For details about the APIs, please refer to the API Reference.

API Description
fetch(request: Request): Promise<Response> Sends an HTTP request and obtains an HTTP response from the server. This API returns the result asynchronously through a promise.

[h2]Example

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Create a Request object. Replace https://www.example.com with the actual URL to request.

    // The URL to request is only an example. Modify it as needed.
    const kHttpServerAddress = 'https://www.example.com/fetch';
    const request = new rcp.Request(kHttpServerAddress, 'GET');
  3. Create a session.

    const session = rcp.createSession();
  4. Initiate a request and process the returned result.

    session.fetch(request).then((rep: rcp.Response) => {
      console.info(`Response succeeded: ${rep}`);
      // ...
    }).catch((err: BusinessError) => {
      // Process the error. The error is captured by a catch block, and then processed. In this example, the error message is displayed on the console.
      console.error(`Response error code is ${err.code}, error data is ${err.data}`);
    });

Initiating a GET Network Request

Sending HTTP GET requests is one of the most common communication methods. To implement this efficiently, Remote Communication Kit adopts a combined strategy of promises and asynchronous callbacks. This not only enables efficient data retrieval from the server but also enhances code readability and maintainability.

[h2]API Description

For details about the APIs, please refer to the API Reference.

API Description
get(url: URLOrString, destination?: ResponseBodyDestination): Promise<Response> Sends an HTTP GET request with the default HTTP parameters and obtains an HTTP response from the server. The parameters specify the URL to request and desired response. This API returns the result asynchronously through a promise.

[h2]Example

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Create a session and initiate a GET request.

    // 1. Define the request URL. The following is only an example. Replace it with the actual one.
    const getURL = 'http://www.example.com/get';
    
    // 2. Create a session.
    const session = rcp.createSession();
    
    // 3. Initiate a request using session.get, with getURL passed as the input parameter. It uses a promise to return the result asynchronously.
    session.get(getURL).then((response) => {
      console.info(`Response succeeded: ${response}`);
      // ...
    }).catch((err: BusinessError) => {
      // 4. Process the error. The error is captured by a catch block, and then processed. In this example, the error message is displayed on the console.
      console.error(`Response error code is ${err.code}, error data is ${err.data}`);
    });

Initiating a POST Network Request

Your app can send an HTTP POST request with the default HTTP parameters and obtain an HTTP response from the server. In the process, the called API returns the result asynchronously through a promise. This capability is used to submit data to the server. Unlike a GET request, in a POST request, the request body carries parameters. Such requests can be used to create resources, submit form data, or execute specific operations.

[h2]API Description

For details about the APIs, please refer to the API Reference.

API Description
post(url: URLOrString, content?: RequestContent, destination?: ResponseBodyDestination): Promise<Response> Sends an HTTP POST request with the default HTTP parameters and obtains an HTTP response from the server. This API returns the result asynchronously through a promise.

[h2]Example

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Create a session and initiate a POST request.

    // Define the URL. The following URL is only an example. You can replace the URL with the actual one.
    const postURL = 'https://www.example.com';
    // Define the content as required.
    const postContent: rcp.RequestContent = {
      fields: {
        'key1': 'value1',
        'key2': 'value2',
        'key3': 'value3'
      }
    }
    // Create a session.
    const session = rcp.createSession();
    // Initiate a POST request and use a promise to return the result asynchronously. In the request, optionally include content and destination as input parameters based on your needs.
    session.post(postURL, postContent)
      .then((response) => {
        console.info(`Response succeeded: ${JSON.stringify(response.headers)}`);
        console.info(`Response succeeded: ${JSON.stringify(response.statusCode)}`);
        console.info(`Response succeeded: ${JSON.stringify(postContent)}`);
        // ...
      })
      .catch((err: BusinessError) => {
        console.error(`Response error code is ${err.code}, error data is ${err.data}`);
      })

Initiating a PUT Network Request

In the framework of Remote Communication Kit, an HTTP PUT request is used to update a specific resource on the server. It performs an idempotent operation, ensuring that only the target resource status changes. The framework uses the promise asynchronous programming model, allowing you to effectively manage and control the execution flow of requests and handle asynchronous operations and their responses in a structured way.

[h2]API Description

For details about the APIs, please refer to the API Reference.

API Description
put(url: URLOrString, content?: RequestContent, destination?: ResponseBodyDestination): Promise<Response> Sends an HTTP PUT request with the default HTTP parameters and obtains an HTTP response from the server. This API returns the result asynchronously through a promise.

[h2]Example

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Create a session and initiate a PUT request.

    // Create a session.
    const session = rcp.createSession();
    
    // Define the content as required.
    const postContent: rcp.RequestContent = {
      fields: {
        'key1': 'value1',
        'key2': 'value2',
        'key3': 'value3'
      }
    }
    
    // Initiate a PUT request through the session, and replace http://www.example.com/put with the URL to request as required.
    session.put('http://www.example.com/put', postContent).then((response) => {
      // Process the response. The following is an example, which only displays the response.
      console.info(`Response succeeded: ${response}`);
      // ...
    }).catch((err: BusinessError) => {
      // Process the result error.
      console.error(`Response error code is ${err.code}, error data is ${err.data}`);
    });

Initiating a HEAD Network Request

An HTTP HEAD request can efficiently access server resource header information. Such requests are similar to GET requests, but with a key difference: HEAD requests only return response headers, not the actual content. This makes them highly efficient for retrieving metadata about a resource, such as the file size, modification date, and whether a resource has been modified.

[h2]API Description

For details about the APIs, please refer to the API Reference.

API Description
head(url: URLOrString): Promise<Response> Sends an HTTP HEAD request with the default HTTP parameters and obtains an HTTP response from the server. This API returns the result asynchronously through a promise.

[h2]Example

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Create a session and initiate a HEAD request.

    // 1. Create a session.
    const session = rcp.createSession();
    
    // 2. Initiate a HEAD request through the session, and replace http://www.example.com/head with the actual URL to request.
    session.head('http://www.example.com/head').then((response) => {
      // 3. Process the response. The following is an example, which only displays the response.
      console.info(`Response succeeded: ${response}`);
      // ...
    }).catch((err: BusinessError) => {
      // 4. Process the result error.
      console.error(`Response error code is ${err.code}, error data is ${err.data}`);
    });

Initiating a DELETE Network Request

In the framework of Remote Communication Kit, the kit employs a combined approach of initiating HTTP DELETE requests that use a promise to return the result asynchronously. Specifically, by sending an HTTP DELETE request with the default HTTP parameters to a predefined URL, resources associated with the target URL can be deleted efficiently. This mechanism not only simplifies the request sending process but also enhances asynchronous handling efficiency, ensuring flexible and responsive resource management.

[h2]API Description

For details about the APIs, please refer to the API Reference.

API Description
delete(url: URLOrString): Promise<Response> Sends an HTTP DELETE request with the default HTTP parameters and obtains an HTTP response from the server. This API returns the result asynchronously through a promise.

[h2]Example

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    const session = rcp.createSession();
    // The URL to request is only an example. Modify it as needed.
    session.delete('http://www.example.com/delete').then((response) => {
      console.info(`Response succeeded: ${response}`);
      // ...
    }).catch((err: BusinessError) => {
      console.error(`Response error code is ${err.code}, error data is ${err.data}`);
    });

Sending HTTP Simple Form Data Using Form

When you use RequestContent to specify the data to be sent in an HTTP request, you can use Form to send HTTP simple form data.

Since version 6.0.1(21), you can specify the order for sending keys in a form.

[h2]Example

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Create RequestContent.

    // Create the form data.
    const simpleForm = new rcp.Form({
      'key1': 'value1',
      'key2': 'value2',
    });
    // Specify the sending order of keys in the form. If this parameter is set, the keys are sent based on the order in the configured list. Keys not in the list are not sent. If this parameter is not set, the default sending order follows the hash sequence of each key.
    simpleForm.keys = ['key2', 'key1'];
    // Create a request. Replace the URL with the actual address.
    let req = new rcp.Request('https://example.com');
    req.content = simpleForm;
  3. Create a session and send a FETCH request.

    try {
      // Create a session.
      const session = rcp.createSession();
      // Initiate a request using the session.
      session.fetch(req).then((resp: rcp.Response) => {
        console.info(`Response succeeded: ${JSON.stringify(resp.statusCode)}`);
        // ...
        session.close();
      }).catch((err: BusinessError) => {
        // Process the result error.
        console.error(`Response error code is ${err.code}, error data is ${err.data}`);
        session.close();
      })
    } catch (err) {
      // Process the session creation error.
      console.error(`createSession error code is ${err.code}, error data is ${err.data}`);
    }

Sending HTTP Multi-Part Form Data Using MultipartForm

When you use RequestContent to specify the data to be sent in an HTTP request, you can use MultipartForm to send HTTP multi-part form data.

Since version 6.0.1(21), you can specify the order for sending keys in a multi-part form.

[h2]Example

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Create RequestContent.

    // Create the multi-part form data.
    const multiForm = new rcp.MultipartForm({
      'key1': 'value1',
      'key2': 'value2',
      'key3': 'value3',
    });
    // Specify the sending order of keys in the multi-part form. If this parameter is set, the keys are sent based on the order in the configured list. Keys not in the list are not sent. If this parameter is not set, the default sending order follows the hash sequence of each key.
    multiForm.keys = ['key3', 'key1', 'key2'];
    // Create a request. Replace the URL with the actual address.
    let req = new rcp.Request('https://example.com');
    req.content = multiForm;
  3. Create a session and send a FETCH request.

    try {
      // Create a session.
      const session = rcp.createSession();
      // Initiate a request using the session.
      session.fetch(req).then((resp: rcp.Response) => {
        console.info(`Response succeeded: ${JSON.stringify(resp.statusCode)}`);
        this.textArea = JSON.stringify(resp.statusCode, null, 2);
        session.close();
      }).catch((err: BusinessError) => {
        // Process the result error.
        console.error(`Response error code is ${err.code}, error data is ${err.data}`);
        session.close();
      })
    } catch (err) {
      // Process the session creation error.
      console.error(`createSession error code is ${err.code}, error data is ${err.data}`);
    }