Mastering Network Requests in HarmonyOS NEXT: A Practical Guide from Novice to Expert

Feri一到,编程开窍,嗨,我是Feri!
When Feri arrives, programming becomes a breeze. Hi, I'm Feri!
🚀 Mastering Network Requests in HarmonyOS NEXT: A Practical Guide from Novice to Expert
I. Why Do We Need Network Requests? The "Food Delivery Philosophy" for Programmers
Imagine you're developing a news app. When users tap the screen, you need to fetch the latest news from the server. It's just like ordering food delivery:
URL is the restaurant's address (e.g.,
https://www.juhe.cn/news/api
).Request Methods are your ways of placing an order:
GET
is like asking the chef, "Give me a serving of Kung Pao Chicken" (retrieving data).POST
is like submitting an order (sending data to the server).
Request Parameters are your special requests: for example, "mildly spicy with less rice" (
type=tech&page=1
).Response Results are the food boxes delivered by the delivery person (possibly news data in JSON format).
Once you understand this analogy, we can start getting our hands dirty!
II. HTTP Basics: The "Network Conversation" Rules for Programmers
1. Eight Request Methods: How Should You "Speak"?
Method | Function | Analogous Scenario |
GET | Retrieve resources (read-only) | Checking the menu |
POST | Create resources (add new data) | Submitting an order |
PUT | Update resources (modify data) | Modifying an order (e.g., changing a drink) |
DELETE | Delete resources | Canceling an order |
HEAD | Retrieve only the response headers (not the body) | Asking the chef, "Is this dish spicy?" |
OPTIONS | Check the methods supported by an interface | Asking the waiter, "Do you accept card payments?" |
💡 In development,
GET
andPOST
are the most commonly used methods. However, mastering the entire family will help you handle complex scenarios!
2. JSON: The "Universal Language" for Programmers
JSON looks like this:
{
"news": [
{
"title": "HarmonyOS Network Request Practice",
"author": "Feri",
"tags": ["programming", "HarmonyOS", "network development"]
}
]
}
Objects
{}
: They're like drawers, holding compartments of "property name: value".Arrays
[]
: They're like boxes, holding multiple objects or values.Language-Agnostic: Whether you're using Java or JavaScript, you can understand this "alien language".
III. The First Step in Practice: Initiating Your First Request (Using a News API as an Example)
1. Preparation: Applying for a "Network Pass"
Add this line to config.json
(otherwise, the request will be blocked):
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
2. Three Steps in Code (Taking a GET Request as an Example)
① Import the Toolkit: Open the "Network Toolbox"
import { http } from '@kit.NetworkKit'; // Import network tools
② Create a Request Object: Get the "Order Menu"
let request = http.createHttp(); // It's like getting a blank order form
③ Initiate the Request: Click the "Place Order" Button
Button("Get Top News")
.onClick(async () => {
const API_KEY = "7f14068bf84db1f93377e4a98c8c8404"; // Your API key (like an order password)
const url = `http://v.juhe.cn/toutiao/index?key=${API_KEY}&type=top`; // Concatenate the full address
// Initiate the request. Here, async/await is used to make the code feel more synchronous.
const response = await request.request(url, {
method: http.RequestMethod.GET, // Tell the server, "I want to retrieve data"
header: { "Content-Type": "application/x-www-form-urlencoded" } // Request header: Tell the server the data format
});
// Process the result: It's like opening the food delivery box.
if (response.responseCode === 200) { // 200 means "order successful"
const newsData = JSON.parse(response.result); // Parse the JSON data
console.log("Latest News:", newsData.data[0].title); // Print the title of the first news item
} else {
console.log("Request failed, error code:", response.responseCode);
}
request.destroy(); // Remember to clean up after eating (release resources)
})
IV. Advanced Operations: Encapsulating Utility Classes — Making Code More Elegant
Imagine having to repeatedly write the address and phone number every time you order food. Isn't that troublesome? Encapsulating utility classes is like creating "common order templates" that you can use directly next time.
1. Encapsulate HttpUtil (Supports Promises and Interceptors)
import { http } from '@kit.NetworkKit';
export class HttpUtil {
// Default configuration: such as common timeout and data format
static DEFAULT_CONFIG = {
timeout: 10000, // 10-second timeout
headers: { "Content-Type": "application/json" }
};
// Generic request method (supports all request types)
static async request(url: string, options: any) {
const config = { ...this.DEFAULT_CONFIG, ...options };
const request = http.createHttp();
try {
const res = await request.request(url, {
method: config.method,
header: config.headers,
extraData: config.data, // Parameters for POST requests
connectTimeout: config.timeout,
readTimeout: config.timeout
});
if (res.responseCode >= 200 && res.responseCode < 300) {
return JSON.parse(res.result); // Automatically parse JSON
} else {
throw new Error(`Request failed: ${res.responseCode}`);
}
} finally {
request.destroy(); // Remember to release resources!
}
}
// Quick GET method (automatically concatenates parameters)
static get(url: string, params?: any) {
const query = params ? new URLSearchParams(params).toString() : "";
return this.request(`${url}?${query}`, { method: http.RequestMethod.GET });
}
// Quick POST method
static post(url: string, data?: any) {
return this.request(url, { method: http.RequestMethod.POST, data });
}
}
2. Using the Utility Class: Initiate a Request with One Line of Code
// Get a joke (GET request)
Button("Tell Me a Joke")
.onClick(async () => {
const joke = await HttpUtil.get("http://v.juhe.cn/joke/randJoke", {
key: "b12d46180eda262ec3a1cec558aa950e"
});
console.log(joke.result.joke); // Get the joke content directly
})
// Submit a form (POST request)
Button("Submit Feedback")
.onClick(async () => {
const feedback = {
content: "This utility class is amazing!",
userId: "12345"
};
await HttpUtil.post("http://api.example.com/feedback", feedback);
console.log("Feedback submitted successfully!");
})
V. Pitfall Guide: I've Filled These Holes for You!
Forgetting to Add Network Permissions: You'll get an error like
net::ERR_CLEARTEXT_NOT_PERMITTED
. Remember to checkconfig.json
!Incorrect Parameter Format: For GET requests, parameters should be appended to the URL (using
?key=value&...
), and for POST requests, parameters should be in JSON format.Cross-Origin Issues: If you're debugging locally, the server needs to set the
Access-Control-Allow-Origin
header.Memory Leaks: Always call
request.destroy()
after each request; otherwise, it will lead to memory overflow!
VI. Expanded Thinking: How to Make Requests More Powerful?
Interceptors: You can uniformly add tokens (e.g.,
Authorization: Bearer xxx
) before requests and uniformly handle error codes (e.g., redirect to the login page for a 401 error) after responses.Caching Mechanisms: Add caching for frequently accessed interfaces (such as home page data) to reduce server load.
Retry Mechanisms: Automatically retry requests that time out or return a 500 error (e.g., retry up to 3 times with a 1-second interval between each retry).
Conclusion: From Manual Labor to Tool Building, You've Progressed!
Now you've mastered the core of network requests in HarmonyOS:
Basic concepts (HTTP methods, JSON format)
Practical skills (initiating requests, handling responses)
Advanced capabilities (encapsulating utility classes, solving common problems)
Next, try to develop a complete news app using today's knowledge. Remember, when you encounter problems, think of network requests as "ordering food delivery" and break down the problems step by step. You'll find that everything is much simpler than you thought!
If you find this useful, feel free to like, bookmark, and follow me for more tips on programmer growth. See you in the next issue! 👋
Where there is a will, there is a way! May you always maintain a passion for exploration in the world of code 🔥
Subscribe to my newsletter
Read articles from CoderFeri directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
