鸿蒙掌上驾考宝典应用开发23:鸿蒙网络请求封装——Axios 库实践
·
第23篇:鸿蒙网络请求封装——Axios 库实践

一、引言
网络请求是应用与后端通信的基础。DriverLicenseExam 项目使用 @ohos/axios 库封装了统一的网络请求层,支持请求/响应拦截器、Mock 数据切换等特性。本文将深入解析网络层的设计与实现。
二、AxiosHttpModel 封装
2.1 类设计
// commons/network/src/main/ets/models/AxiosHttpModel.ets
export class AxiosHttpModel {
private _instance: AxiosInstance;
private _openMock: boolean;
private _config: HttpRequestConfig;
constructor(config: HttpRequestConfig, openMock: boolean = false) {
this._config = config;
this._instance = axios.create(config);
this._openMock = openMock;
this._setupInterceptor();
}
}
2.2 请求方法
// 通用请求
public request<T = ESObject>(config: HttpRequestConfig): Promise<T> {
return new Promise<T>((resolve, reject) => {
this._instance
.request<ESObject, T>(config)
.then(res => resolve(res))
.catch(err => {
Logger.error('https request failed:${config.url}', err.message);
reject(err);
});
});
}
// GET 请求
public get<T = ESObject>(config: HttpRequestConfig): Promise<T> {
config.method = 'GET';
return this.request(config);
}
// POST 请求
public post<T = ESObject>(config: HttpRequestConfig): Promise<T> {
config.method = 'POST';
return this.request(config);
}
// DELETE 请求
public delete<T = ESObject>(config: HttpRequestConfig): Promise<T> {
config.method = 'DELETE';
return this.request(config);
}
三、拦截器机制
private _setupInterceptor(): void {
if (this._config.interceptorHooks) {
// 请求拦截器
this._instance.interceptors.request.use(
this._config.interceptorHooks.requestInterceptor,
this._config.interceptorHooks.requestInterceptorCatch,
);
// 响应拦截器
this._instance.interceptors.response.use(
this._config.interceptorHooks.responseInterceptor,
this._openMock ? this._replaceMock : this._config.interceptorHooks.responseInterceptorCatch,
);
}
}
四、API 接口层
// commons/network/src/main/ets/apis/HttpApis.ets
class HttpApi {
public bindPhone(authCode: string): Promise<BaseResponse<undefined>> {
return request.post({
url: RequestUrl.USER_BIND_PHONE,
data: { authCode },
});
}
public getUserInfo(): Promise<BaseResponse<GetUserInfoResp>> {
return request.get({ url: RequestUrl.USER_GET_INFO });
}
}
const https = new HttpApi();
export { https };
五、Mock 数据切换
// Mock 数据
class HttpApiMock {
public getUserInfo(): Promise<BaseResponse<GetUserInfoResp>> {
const resp: BaseResponse = { code: 0, data: { avatar: 'mockImage://ic_default_avatar', nickname: '', phone: '1XXXXXX' } };
return Promise.resolve(resp);
}
}
const httpsMock = new HttpApiMock();
export { httpsMock };
六、总结
网络层通过 AxiosHttpModel 封装了统一的请求接口,支持拦截器、Mock 切换等特性,为上层业务提供简洁的网络调用 API。
关键源码文件:
commons/network/src/main/ets/models/AxiosHttpModel.etscommons/network/src/main/ets/apis/HttpApis.etscommons/network/src/main/ets/mocks/HttpApisMock.etscommons/network/src/main/ets/types/ResponseTypes.ets
更多推荐

所有评论(0)