各位鸿蒙开发者!网络通信是鸿蒙应用开发的核心模块,也是认证中占比 16% 的高频考点 —— 从 HTTPS 请求封装、JSON 数据解析到异常处理,全程贴合认证大纲,今天咱们手把手拆解实战代码,覆盖所有必考点,看完就能落地项目!

一、网络通信核心考点(认证必懂)

1. 考点分值分布

考点类型

分值占比

核心考查内容

HttpClient 基础

4 分

请求创建、参数配置、客户端销毁

HTTPS 请求实现

5 分

证书处理、请求头设置、POST/GET 用法

JSON 数据解析

3 分

序列化 / 反序列化、复杂数据结构解析

异常处理

2 分

网络异常、状态码处理、断网提示

工具类封装

2 分

复用性设计、统一响应处理

2. 核心原则(认证踩分点)

  • 鸿蒙 5.0+ 强制要求HTTPS 请求(HTTP 请求需额外配置,认证优先考 HTTPS);
  • 必须手动销毁HttpClient(避免内存泄漏,认证高频扣分点);
  • 网络请求需在非 UI 线程执行(鸿蒙自动处理,但需避免同步阻塞);
  • 必须申请INTERNET权限(配置 + 动态申请,缺一不可)。

二、前置准备(认证必配步骤)

1. 权限配置(module.json5)


{

"module": {

"requestPermissions": [

{

"name": "ohos.permission.INTERNET", // 网络核心权限

"reason": "需要访问网络获取/提交数据",

"usedScene": {

"abilities": ["*"],

"when": "always"

             }

         }

       ]

    }

}

⚠️ 认证考点标红:权限配置是必考点,缺失会导致请求失败,实操考试直接扣分!

2. 开发环境要求

  • DevEco Studio 4.0+
  • 鸿蒙 SDK 5.0+
  • 测试设备:真机 / 模拟器(需联网,模拟器需配置网络权限)

三、核心 API 详解(认证高频)

鸿蒙网络通信核心依赖@ohos.net.http模块,关键 API 如下(标红为认证重点):

API 方法

作用

认证考查点

http.createHttp()

创建 HttpClient 实例

实例创建时机、避免重复创建

httpClient.request()

发送网络请求

参数配置、回调 / 异步处理

httpClient.destroy()

销毁 HttpClient

必须调用,否则内存泄漏

JSON.parse()

JSON 字符串转对象

复杂数据结构解析

JSON.stringify()

对象转 JSON 字符串

请求体序列化

四、实战实现(含完整源码)

模块 1:网络工具类封装(认证加分项)

封装通用网络工具类,实现请求复用、统一响应处理,贴合实际开发场景:


// utils/HttpUtil.ets(认证标准实现)

import http from '@ohos.net.http';

import promptAction from '@ohos.promptAction';

import { BusinessError } from '@ohos.base';

// 基础URL(实际项目替换为真实接口)

export const BASE_URL = 'https://jsonplaceholder.typicode.com'; // 测试接口

// 网络请求配置项

interface RequestConfig {

url: string;

method: http.RequestMethod; // GET/POST/PUT/DELETE

data?: any; // 请求体(POST/PUT用)

header?: Record string>; // 请求头

}

// 响应数据结构(统一格式)

interface ResponseResult {

code: number; // 状态码

data: T | null; // 响应数据

message: string; // 提示信息

}

// 网络工具类(单例模式,认证推荐)

export class HttpUtil {

private static instance: HttpUtil;

// 单例创建(避免重复实例化)

public static getInstance(): HttpUtil {

if (!HttpUtil.instance) {

HttpUtil.instance = new HttpUtil();

}

return HttpUtil.instance;

}

// 通用请求方法(核心实现)

public async request: RequestConfig): Promise<ResponseResult // 1. 创建HttpClient实例

const httpClient = http.createHttp();

try {

// 2. 配置请求参数

const defaultHeader = {

'Content-Type': 'application/json', // 默认JSON格式

'User-Agent': 'HarmonyOS-App/1.0'

};

const requestOptions: http.HttpRequestOptions = {

method: config.method,

header: { ...defaultHeader, ...config.header },

extraData: config.data ? JSON.stringify(config.data) : '', // 序列化请求体

connectTimeout: 10000, // 超时时间(10秒,认证考点)

readTimeout: 10000

};

// 3. 发送请求(异步执行,不阻塞UI)

const response = await httpClient.request(

`${BASE_URL}${config.url}`,

requestOptions

);

// 4. 响应处理(认证核心踩分点)

if (response.responseCode === 200 || response.responseCode === 201) {

// 成功:JSON解析

const result = JSON.parse(response.result.toString()) as T;

return {

code: response.responseCode,

data: result,

message: '请求成功'

};

} else {

// 失败:状态码处理

promptAction.showToast({ message: `请求失败:${response.responseCode}` });

return {

code: response.responseCode,

data: null,

message: `状态码:${response.responseCode}`

};

}

} catch (err) {

// 5. 异常处理(网络异常/解析异常,认证必考点)

const error = err as BusinessError;

let errMsg = '网络异常';

if (error.code === 100) errMsg = '无网络连接';

if (error.code === 101) errMsg = '连接超时';

promptAction.showToast({ message: errMsg });

return {

code: error.code || -1,

data: null,

message: errMsg

};

} finally {

// 6. 销毁HttpClient(认证高频扣分点,必须执行)

httpClient.destroy();

}

}

// GET请求(简化调用)

public get>(url: string, header?: Record): Promise<ResponseResult>> {

return this.request url,

method: http.RequestMethod.GET,

header

});

}

// POST请求(简化调用)

public post: string, data?: any, header?: Record string>): PromiseResult return this.request

url,

method: http.RequestMethod.POST,

data,

header

});

}

}

// 导出单例(全局复用)

export const httpUtil = HttpUtil.getInstance();

模块 2:JSON 数据解析实战(认证重点)

2.1 数据模型定义(贴合真实场景)

// model/PostModel.ets(复杂数据结构示例)

// 响应数据模型(与接口返回格式一致)

export interface Post {

id: number;

userId: number;

title: string;

body: string;

tags?: string[]; // 可选字段

comments?: Comment[]; // 嵌套字段(认证考点)

}

// 嵌套数据模型

export interface Comment {

id: number;

name: string;

email: string;

body: string;

}
2.2 解析实战(GET/POST 示例)

// pages/NetworkTestPage.ets

import { httpUtil } from '../utils/HttpUtil';

import { Post } from '../model/PostModel';

import promptAction from '@ohos.promptAction';

import { ScrollView, Text, Button, Column, Row, TextInput, FlexAlign } from '@ohos.ui.components';

@Entry

@Component

struct NetworkTestPage {

@State postList: Post[] = [];

@State inputTitle: string = '';

@State inputBody: string = '';

// GET请求:获取文章列表(认证高频场景)

async getPostList() {

const result = await httpUtil.get<Post[]>('/posts'); // 测试接口

if (result.code === 200 && result.data) {

this.postList = result.data.slice(0, 10); // 取前10条数据

promptAction.showToast({ message: `获取成功:${this.postList.length}条` });

}

}

// POST请求:提交数据(认证高频场景)

async submitPost() {

if (!this.inputTitle || !this.inputBody) {

promptAction.showToast({ message: '请输入标题和内容' });

return;

}

// 构造请求体

const postData = {

title: this.inputTitle,

body: this.inputBody,

userId: 1

};

const result = await httpUtil.post>('/posts', postData);

if (result.code === 201) {

promptAction.showToast({ message: '提交成功!' });

this.inputTitle = '';

this.inputBody = '';

this.getPostList(); // 刷新列表

}

}

build() {

Column({ space: 15 }) {

Text('鸿蒙网络通信实战(HTTPS)')

.fontSize(22)

.fontWeight(FontWeight.Bold)

.width('100%')

.textAlign(TextAlign.Center)

.padding(10);

// 功能按钮组

Row({ space: 10, justifyContent: FlexAlign.Center }) {

Button('获取文章列表(GET)')

.width('45%')

.height(45)

.backgroundColor('#007dff')

.fontColor('#fff')

.onClick(() => this.getPostList());

Button('提交文章(POST)')

.width('45%')

.height(45)

.backgroundColor('#00c853')

.fontColor('#fff')

.onClick(() => this.submitPost());

}

// 提交表单

Column({ space: 10 }) {

TextInput({ placeholder: '输入文章标题' })

.width('90%')

.height(45)

.padding(10)

.backgroundColor('#f5f5f5')

.borderRadius(8)

.onChange((value) => this.inputTitle = value);

TextInput({ placeholder: '输入文章内容' })

.width('90%')

.height(80)

.padding(10)

.backgroundColor('#f5f5f5')

.borderRadius(8)

.multiline(true)

.onChange((value) => this.inputBody = value);

}

.padding(10);

// 结果展示

ScrollView() {

Column({ space: 10 }) {

ForEach(this.postList, (item) => {

Column({ space: 5 }) {

Text(item.title)

.fontSize(18)

.fontWeight(FontWeight.Bold)

.width('100%');

Text(item.body)

.fontSize(14)

.fontColor('#666')

.width('100%');

Divider().color('#eee');

}

.padding(10)

.width('90%')

.backgroundColor('#fff')

.borderRadius(8);

});

}

.padding(10);

}

.flexGrow(1)

.width('100%');

}

.width('100%')

.height('100%')

.backgroundColor('#f9f9f9');

}

}

模块 3:HTTPS 证书处理(认证进阶考点)

鸿蒙 5.0+ 默认信任系统根证书,若接口使用自签名证书,需手动配置证书校验(认证选考,实操加分):


// utils/HttpsCertUtil.ets(自签名证书处理)

import http from '@ohos.net.http';

import fs from '@ohos.file.fs';

// 读取本地证书文件(需将.pem证书放入main_pages文件夹)

async function getCertContent(context: Context): Promise> {

const certPath = `${context.filesDir}/cert.pem`; // 证书路径

const file = await fs.open(certPath, fs.OpenMode.READ_ONLY);

const buffer = await fs.read(file.fd, { length: file.size });

await fs.close(file.fd);

return buffer.buffer as Uint8Array;

}

// 配置HTTPS证书校验

export async function configHttpsCert(httpClient: http.HttpClient, context: Context) {

try {

const certContent = await getCertContent(context);

// 设置证书校验模式(自签名证书用CERTIFICATE_MODE_REQUIRED)

httpClient.setCertMode(http.CertMode.CERTIFICATE_MODE_REQUIRED);

// 添加自定义证书

httpClient.addCertificate('custom_cert', certContent, http.CertType.PEM);

} catch (err) {

console.error(`证书配置失败:${err.message}`);

}

}

// 用法:在HttpUtil的request方法中添加

// const certContent = await getCertContent(context);

// httpClient.addCertificate('custom_cert', certContent, http.CertType.PEM);

五、认证核心考点总结(实战对应)

考点

实战体现

扣分点预警

INTERNET 权限配置

module.json5 权限声明

未配置权限,请求直接失败

HttpClient 销毁

finally 块中调用 destroy ()

未销毁,内存泄漏,实操直接扣分

异步请求处理

await 关键字 + async 函数

同步请求阻塞 UI,认证扣分

JSON 解析

Post 模型定义 + JSON.parse ()

嵌套字段解析错误,逻辑扣分

异常处理

BusinessError 捕获 + 错误提示

未处理异常,程序崩溃,无法通过测试

请求头设置

defaultHeader 配置 Content-Type

未设置 JSON 格式,接口返回 400

六、实战优化(认证加分项)

1.请求拦截器:添加统一 Token、日志打印(认证进阶考点);

// 拦截器示例(HttpUtil中扩展)

private addInterceptor(httpClient: http.HttpClient) {

httpClient.on('request', (request) => {

// 添加Token

request.header['Authorization'] = 'Bearer ' + getToken();

console.log(`请求URL:${request.url}`);

});

}

2.缓存策略:结合 Preferences 缓存 GET 请求结果(断网时使用);

3.重试机制:网络恢复时自动重试失败请求(最多 3 次);

4.进度回调:大文件上传 / 下载时,用onProgress监听进度。

七、常见问题排查(认证避坑)

  1. 请求失败,状态码 403:检查 HTTPS 配置,确认接口支持 TLS 1.2+;
  2. JSON 解析报错:确保模型字段与接口返回一致(可选字段用?标记);
  3. 模拟器请求失败:检查模拟器网络连接,重启 DevEco Studio 网络服务;
  4. 内存泄漏警告:确认每次请求后都调用httpClient.destroy()。

八、源码使用说明

  1. 复制上述代码到 DevEco Studio,确保 SDK 版本≥5.0;
  2. 测试接口使用jsonplaceholder.typicode.com(免费公开,无需注册);
  3. 自签名证书处理为进阶内容,认证基础考试可不涉及,实操加分时使用。

七、班级
目前班级正火热招募学员!加入班级:https://developer.huawei.com/consumer/cn/training/classDetail/6b5617ffd9264d6daa2f3d9250204f1e?type=1%3Fha_source%3Dhmosclass&ha_sourceId=89000248,跟着系列文章系统学,快速掌握鸿蒙开发核心技能,冲刺 HarmonyOS 应用开发者认证!无论你是零基础入门,还是在职开发者提升,都能在班级中收获成长,抢占鸿蒙生态人才红利~
 
 

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐