Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing HTTP Data Requests with Axios in HarmonyOS

Tech Apr 14 19

Configuring Network Permissions in module.json5

To enable network access for your HarmonyOS application, you must declare the internet permission in your module.json5 file.

"requestPermissions": [{
  "name": "ohos.permission.INTERNET"
}]

Installing the Axios Library

Instal the @ohos/axios package using the OpenHarmony Package Manager (OHPM). You can execute the following command in your project's terminal:

ohpm install @ohos/axios

Implementing HTTP Requests with Axios

Below is a complete example demonstrating how to use Axios to fetch data from a public API endpoint.

// Import the Axios library and its types
import axios, { AxiosError, AxiosResponse } from '@ohos/axios';

// Define the structure for the API response data
class ApiResponse {
  items: Array<ChatRecord> = [];
}

class ChatRecord {
  sender: string = '';
  avatar: string = '';
  description: string = '';
  nickname: string = '';
  content: string = '';
}

// Public test API endpoint
const testApiUrl = 'http://rap2api.taobao.org/app/mock/293606/api/chat/list';

@Entry
@Component
struct NetworkRequestDemo {
  @State chatRecords: Array<ChatRecord> = [];
  apiEndpoint = testApiUrl;

  build() {
    Row() {
      Column() {
        // Button to trigger a simple GET request
        Button('Fetch Data with GET')
          .margin(20)
          .onClick(() => {
            this.performGetRequest();
          });

        // Display the fetched data
        ForEach(this.chatRecords, (record: ChatRecord) => {
          Text(record.sender).fontColor(Color.Red);
        });

        // Button to trigger a typed GET request with error handling
        Button('Fetch Data with Error Handling')
          .margin(20)
          .onClick(() => {
            this.fetchDataWithTypes();
          });

        ForEach(this.chatRecords, (record: ChatRecord) => {
          Text(record.sender).fontColor(Color.Blue);
        });
      }
      .width('100%');
    }
    .height('100%');
  }

  // Method for a basic GET request
  performGetRequest() {
    axios.get(this.apiEndpoint)
      .then((response: AxiosResponse) => {
        AlertDialog.show({ message: JSON.stringify(response.data) });
        this.chatRecords = response.data.list;
      });
  }

  // Method for a typed GET request with comprehensive error handling
  fetchDataWithTypes() {
    axios.get<ApiResponse, AxiosResponse<ApiResponse>, null>(testApiUrl)
      .then((resp: AxiosResponse<ApiResponse>) => {
        if (resp.status === 200) {
          AlertDialog.show({ message: JSON.stringify(resp.data.items) });
          this.chatRecords = resp.data.items;
        } else {
          AlertDialog.show({ message: 'Request failed with status: ' + resp.status });
        }
      })
      .catch((error: AxiosError) => {
        AlertDialog.show({ message: 'Network or API error occurred.' });
      });
  }
}

Testing the Application

  1. Start the HarmonyOS emulatro.
  2. Run your applicasion entry point.
  3. Interact with the buttons in the UI to trigger the network requests and observe the data display and dialog messages.
Tags: HarmonyOS

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.