Implementing HTTP Data Requests with Axios in HarmonyOS
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
- Start the HarmonyOS emulatro.
- Run your applicasion entry point.
- Interact with the buttons in the UI to trigger the network requests and observe the data display and dialog messages.