In today’s mobile internet era, front-end and back-end communication is an essential part of app development. HTTP and WebSocket are two of the most common communication protocols, each playing a crucial role in enabling interaction between client and server. Therefore, mastering network communication is very important.
Before using networking capabilities, you first need to request permissions:
-
ohos.permission.INTERNET
: Grants the app access to the internet. -
ohos.permission.GET_NETWORK_INFO
: Allows access to device network information via API.
HTTP
HTTP (HyperText Transfer Protocol) is a protocol used to transfer hypertext from a web server to a local browser. It defines the request and response format between clients and servers. Common HTTP request types include:
1. GET
- Purpose: Request to retrieve information about a specified resource.
-
Characteristics:
- Safe and idempotent: Does not change the server state; repeated requests yield the same result.
- Can be cached.
- Parameters are passed through the URL.
Example: Loading a webpage, fetching API data.
2. POST
- Purpose: Submit data to a specified resource for processing.
-
Characteristics:
- Not safe and not idempotent: May change server state.
- Parameters are usually placed in the request body.
- Used for creating or updating resources.
Example: Submitting forms, uploading files, creating users.
3. PUT
- Purpose: Update a specified resource.
-
Characteristics:
- Idempotent: Repeating the request has the same effect.
- May create a new resource if it doesn’t exist (depends on server).
Example: Updating user information, modifying configuration files.
4. DELETE
- Purpose: Delete a specified resource.
-
Characteristics:
- Idempotent: Repeating the request won’t change the outcome.
Example: Deleting users, removing files.
5. HEAD
- Purpose: Similar to GET, but only retrieves headers, not the body.
-
Characteristics:
- Safe and idempotent.
Example: Check if a webpage exists, get file size.
HTTP in ArkTS
In ArkTS, you can use the built-in Remote Communication Kit (RCP) to send HTTP requests. This module provides common APIs for network requests. You just need to create a session and then call the appropriate method.
Example of a GET request:
const session = rcp.createSession(); session.get("http://www.example.com/get").then((response) => { console.info(`Response succeeded: ${response}`); }).catch((err: BusinessError) => { console.error(`Response error: Code is ${err.code}, message is ${JSON.stringify(err)}`); });
There’s also another API set called Network Kit, which offers a more detailed, message-based subscription approach for networking.
Additionally, there are third-party libraries that simplify networking, such as @ohos/axios
:
// Send a GET request. axios<string, AxiosResponse<string>, null>({ method: "get", url: 'https://www.xxx.com/info' }).then((res: AxiosResponse) => { console.info('Result: ' + JSON.stringify(res.data)); }).catch((error: AxiosError) => { console.error(error.message); });
The choice of library is personal preference—“to each their own.” However, the common best practice is to wrap the lower-level networking tools into your own utility layer. This decouples the third-party libraries from your business logic. If you ever need to switch networking stacks, you only need to modify the utility layer without touching the core business logic.
WebSocket Protocol
WebSocket is a protocol that enables full-duplex, bidirectional communication over a single TCP connection. It allows the server to proactively push messages to the client, making it ideal for real-time communication such as:
- Online chats
- Live stock quotes
- Multiplayer games
Apps like Xiaohongshu use WebSocket for real-time messaging.
Creating a WebSocket Request
Start by creating an instance:
let ws = webSocket.createWebSocket();
Then register a series of callbacks:
ws.on('open', (err: BusinessError, value: Object) => { console.log("on open, status: " + JSON.stringify(value)); }); ws.on('message', (err: BusinessError, value: string | ArrayBuffer) => { console.log("on message, message: " + value); }); ws.on('close', (err: BusinessError, value: webSocket.CloseResult) => { console.log("on close, code: " + value.code + ", reason: " + value.reason); }); ws.on('error', (err: BusinessError) => { console.log("on error, error: " + JSON.stringify(err)); });
Once callbacks are in place, open the WebSocket connection:
ws.connect(Address, (err: BusinessError, value: boolean) => { if (!err) { console.log("Connected successfully"); } else { console.log("Connection failed. Error: " + JSON.stringify(err)); } });
Here, Address
refers to the WebSocket endpoint (e.g., ws://example.com/socket
).
Sending a Message
Once connected, send messages like this:
ws.send("Hello, server!", (err: BusinessError, value: boolean) => { if (!err) { console.log("Message sent successfully"); } else { console.log("Failed to send message. Error: " + JSON.stringify(err)); } });
Top comments (0)