鸿蒙分享(五):axios网络请求+简单封装

ops/2024/12/13 1:17:35/

代码仓库:share_harmonyos: 鸿蒙分享 鸿蒙api:12

axios开源库地址:OpenHarmony三方库中心仓

1.axios使用

1.安装

ohpm install @ohos/axios

2.添加网络权限

common--src--module.json5 添加如下:

"requestPermissions": [{"name": "ohos.permission.INTERNET"}
]

封装BaseHttp

其他代码查看代码仓库:share_harmonyos: 鸿蒙分享 - Gitee.com

import axios, { AxiosError, AxiosInstance, AxiosProgressEvent, AxiosRequestConfig, AxiosResponse, FormData } from '@ohos/axios';
import { LogUtil } from '@pura/harmony-utils';
import { BannerBean } from '../../bean/BannerBean';
import { OrderDetailBean } from '../../bean/OrderDetailBean';
import { UpLoadFileBean } from '../../bean/UpLoadFileBean';
import { BaseLog } from '../BaseLog';
import { BaseUrl } from '../BaseUrl';
import { BaseDialog } from '../dialog/BaseDialog';
import { BaseError } from './BaseError';
import { BaseRequestSet } from './BaseRequestSet';
import { BaseResponse } from './BaseResponse';export class BaseHttp {// axios 实例private instance: AxiosInstance;// axios 请求配置private config: AxiosRequestConfig = {baseURL: BaseUrl.BASE_URL, // http://xxxx/xxxx/timeout: 10000}// 构造函数初始化public constructor(config?: AxiosRequestConfig) {if (!config) {config = this.config}this.instance = axios.create(config);//定义拦截器this.interceptors();//添加请求头// this.getAxios().defaults.headers.common['code'] = BaseUrl.code;// this.getAxios().defaults.headers.common['tid'] = BaseUrl.tid;// this.getAxios().defaults.headers.common['Token'] = BaseUser.Token();}public getAxios() {return this.instance;}request<T = BaseResponse>(type: RequestType,baseSet: BaseRequestSet,success?: (result: T) => void,fail?: (error: BaseError) => void,complete?: () => void,progress?: (progressEvent: AxiosProgressEvent, progress?: number) => void,) {if (baseSet.isLoading && type != RequestType.upload) {this.showLoading(baseSet.loadingMsg)}let response: Promise<BaseResponse<T>>switch (type) {case RequestType.get:response = this.instance.get<string, BaseResponse<T>>(baseSet?.url, { params: baseSet?.params })breakcase RequestType.post:response = this.instance.post<string, BaseResponse<T>>(baseSet?.url, baseSet?.params)breakcase RequestType.put:response = this.instance.put<string, BaseResponse<T>>(baseSet?.url, baseSet?.params)breakcase RequestType.delete:response = this.instance.delete<string, BaseResponse<T>>(baseSet?.url, baseSet?.params)break//上传case RequestType.upload:response = this.instance.post<string, BaseResponse<T>, FormData>(baseSet?.url, baseSet?.formData, {headers: {'Content-Type': 'multipart/form-data'},onUploadProgress: (progressEvent) => {if (progress && progressEvent && progressEvent.loaded && progressEvent.total) {progressEvent.progress = Math.ceil(progressEvent.loaded / progressEvent.total * 100)if (baseSet.isLoading) {BaseDialog.showProgress(progressEvent.progress)}progress(progressEvent, progressEvent.progress)}}})breakdefault:response = this.instance.get<string, BaseResponse<T>>(baseSet?.url, baseSet?.params)break}response.then((res) => {this.dealwithThen(res, success, fail, baseSet)this.dealwithComplete(complete)}).catch((error: AxiosError) => {this.dealwithCatch(error, fail)this.dealwithComplete(complete)});}//处理成功dealwithThen<T = BaseResponse>(res: BaseResponse<T>, success?: (result: T) => void, fail?: (error: BaseError) => void, baseSet?: BaseRequestSet) {this.hintLoading()if (res.code == 200) {if (success) {baseSet?.formData?.forEach((value: string, key) => {(res.result as UpLoadFileBean).cachePath = value})success(res.result)}} else {if (fail) {let failResult: BaseError = {message: res.message,code: res.code}fail(failResult)}if (baseSet?.isShowToast) {BaseDialog.showToast(res.message)}}}//下载文件downloadFile(baseSet: BaseRequestSet,success?: (result?: string) => void,fail?: (error: BaseError) => void,complete?: () => void,progress?: (progressEvent: AxiosProgressEvent, progress?: number) => void) {axios({url: baseSet.url,method: 'get',filePath: baseSet.filePath,onDownloadProgress: (progressEvent: AxiosProgressEvent) => {if (progress && progressEvent && progressEvent.loaded && progressEvent.total) {progressEvent.progress = Math.ceil(progressEvent.loaded / progressEvent.total * 100)if (baseSet.isLoading) {BaseDialog.showProgress(progressEvent.progress)}progress(progressEvent, progressEvent.progress)}}}).then((res: AxiosResponse<string>) => {if (res.status == 200) {if (success) {success(res.config.filePath)}}if (complete) {if (baseSet.isLoading) {BaseDialog.hideProgress()}complete()}}).catch((error: AxiosError) => {let error3: BaseError = {message: error.message,code: error.code ?? error.status ?? 0}if (baseSet.isShowToast) {BaseDialog.showToast(error3.message)}if (baseSet.isLoading) {BaseDialog.hideProgress()}if (fail) {fail(error3)}if (complete) {complete()}})}//处理catchdealwithCatch(error: AxiosError, fail?: (error: BaseError) => void) {this.hintLoading()if (fail) {let error3: BaseError = {message: error.message,code: error.code ?? error.status ?? 0}LogUtil.info("接口请求失败:" + error.config?.url + ";" + JSON.stringify(error3) + ";" + JSON.stringify(error))fail(error3)}}//处理catchdealwithComplete(Complete?: () => void) {this.hintLoading()if (Complete) {Complete()}}showLoading(msg: string = "") {BaseDialog.showLoading(msg)}hintLoading() {BaseDialog.hintLoading()}getRotationChartInfo(success?: (result: Array<BannerBean>) => void,fail?: (error: BaseError) => void,complete?: () => void) {let baseSet = new BaseRequestSet()baseSet.isLoading = falsebaseSet.url = BaseUrl.BANNER_LIST //    openAPI/xxx/xxxxthis.request<Array<BannerBean>>(RequestType.get, baseSet, success, fail, complete);}//提交订单submitOrder(classTypeId: string,userCouponId: string,success?: (result: OrderDetailBean) => void,fail?: (error: BaseError) => void,complete?: () => void) {let baseSet = new BaseRequestSet(Object({classTypeId: classTypeId,userCouponId: userCouponId,}))baseSet.isLoading = truebaseSet.url = BaseUrl.SUMMIT_ORDERthis.request<OrderDetailBean>(RequestType.post, baseSet, success, fail, complete);}//上传文件uploadFile(baseSet: BaseRequestSet,success?: (result: UpLoadFileBean) => void,fail?: (error: BaseError) => void,complete?: () => void,progress?: (progressEvent: AxiosProgressEvent, progress?: number) => void,) {baseSet.isLoading = truebaseSet.url = BaseUrl.UPLOAD_URLthis.request<UpLoadFileBean>(RequestType.upload, baseSet, success, fail, complete, progress);}private interceptors() {// 请求返回处理this.instance.interceptors.response.use((res: AxiosResponse) => {BaseLog.i("请求返回拦截:" + JSON.stringify(res))switch (res.data.code) {case BaseUrl.TOKEN_CODE:LogUtil.info("用户信息已失效,请重新登录.")// BaseEmitter.post(BaseEmitter.id_to_login, "")break}return res.data;}, (error: AxiosError) => {LogUtil.error("网络请求错误:", JSON.stringify(error))return Promise.reject(error);})}
}enum RequestType {get = "get",post = "post",put = "put",delete = "delete",upload = "upload",
}export default BaseHttp

BaseHttp使用:

1.设置baseURL

2.添加公共的请求头参数

3.如果需要处理特定的错误代码

4.get请求 BaseHttp添加如下代码:

getRotationChartInfo(success?: (result: Array<BannerBean>) => void,fail?: (error: BaseError) => void,complete?: () => void
) {let baseSet = new BaseRequestSet()baseSet.isLoading = falsebaseSet.url = BaseUrl.BANNER_LIST //    openAPI/xxx/xxxxthis.request<Array<BannerBean>>(RequestType.get, baseSet, success, fail, complete);
}

使用:

BaseText({text: "get",fontColor: $r('app.color.color_DD2942')
}).padding(12).margin(6).onClick(() => {new BaseHttp().getRotationChartInfo((data) => {//成功回调},(error) => {//错误回调},() => {//完成回调},)
})

5.post请求 BaseHttp添加如下代码:

//提交订单
submitOrder(classTypeId: string,userCouponId: string,success?: (result: OrderDetailBean) => void,fail?: (error: BaseError) => void,complete?: () => void
) {let baseSet = new BaseRequestSet(Object({classTypeId: classTypeId,userCouponId: userCouponId,}))baseSet.isLoading = truebaseSet.url = BaseUrl.SUMMIT_ORDERthis.request<OrderDetailBean>(RequestType.post, baseSet, success, fail, complete);
}

使用:

new BaseHttp().submitOrder("","-1",(data) => {},(error) => {},() => {}
)

6.上传文件:

BaseText({text: "上传文件",fontColor: $r('app.color.color_DD2942')
}).padding(12).margin(6).onClick(() => {let baseRequestSet = new BaseRequestSet()baseRequestSet.formData.append('file', "文件url")new BaseHttp().uploadFile(baseRequestSet,(success) => {},(error) => {},() => {},(progressEvent, progress) => {})
})

7.下载文件:

BaseText({text: "下载文件",fontColor: $r('app.color.color_DD2942')
}).padding(12).margin(6).onClick(() => {let baseRequestSet = new BaseRequestSet()baseRequestSet.url = "下载地址"baseRequestSet.filePath = "文件保存地址" //  xxx/xxx.jpgnew BaseHttp().downloadFile(baseRequestSet,(success) => {},(error) => {},() => {},(progressEvent, progress) => {})
})

http://www.ppmy.cn/ops/141391.html

相关文章

ZED相机应用

下载SDK wget https://stereolabs.sfo2.cdn.digitaloceanspaces.com/zedsdk/3.6/ZED_SDK_Ubuntu18_cuda11.5_v3.6.5.run 安装 ./ZED_SDK_Ubuntu18_cuda11.5_v3.6.5.run skip_python 测试 cd /usr/local/zed/tools ls ZED_Calibration ZED_Depth_Viewer ZED_Diagnostic ZED_E…

C++设计模式(建造者、中介者、备忘录)

一、建造者模式 将一个复杂对象的构建与它的表示分离&#xff0c;使得同样的构建过程可以创建不同的表示。 示例&#xff1a; //房子&#xff08;产品类&#xff09; class House { private:int rooms;int windows;string decoration; public:void setRooms(int r) {rooms …

单片机+Qt上位机

目录 一、引言 通信方式 优势 案例 常见问题及解决方法 二、单片机与 Qt 上位机的通信方式 &#xff08;一&#xff09;使用 QT 上位机和 STC 单片机实现串口通信 三、单片机 Qt 上位机的优势 &#xff08;一&#xff09;高效便捷的 USB 通信上位机解决方案 &#xf…

鸿蒙高级开发者认证试题(基础)

目录 一、单选题&#xff08;每题 3 分&#xff0c;共 30 分&#xff09; 二、多选题&#xff08;每题 5 分&#xff0c;共 30 分&#xff09; 以下是一份鸿蒙高级开发者认证试题示例&#xff0c;涵盖了鸿蒙开发相关的多个重要知识点&#xff0c;你可以根据实际情况进行调整和…

数据分析岗位求职攻略 —— 常见面试题目及答案

请简要介绍一下数据分析的过程和方法。 答&#xff1a;数据分析过程通常包括数据采集、数据清理、数据探索、数据建模、和优化模型等步骤。在这个过程中&#xff0c;需要运用统计学、机器学习、数据挖掘、数据可视化等技术方法分析数据的特征&#xff0c;实现数据服务化。 请…

事务的传播机制

事务传播机制的概念&#xff1a; 事务传播机制就是: 多个事务⽅法存在调⽤关系时, 事务是如何在这些⽅法间进⾏传播的。 在我们学习数据库的时候&#xff0c;不存在事务传播机制这个概念&#xff0c;因为数据库是直接执行这个方法而不是有方法之间的互相调用&#xff0c;在我们…

Linux絮絮叨(三) Ubuntu桌面版添加中文拼音输入法

步骤很详细&#xff0c;直接上教程 一. 配置安装简体拼音输入法 #安装相应的平台支持包 sudo apt install ibus-gtk ibus-gtk3# 安装简体拼音输入法 sudo apt install ibus-pinyin安装完成如果下面的步骤找不到对应输入法可以重启一下&#xff0c;一般不需要 二. 添加简体拼音…

C# 关于实现保存数据以及数据溯源推送

前言 实现了一个数据接收、存储和推送的功能 首先定义我们数据存储的格式&#xff08;可根据自己的需求定义格式&#xff09;&#xff1a; 数据切割符号&#xff1a;**$是区分数据与其他数据的划分 数据内容切割号&#xff1a;|**是区分时间戳与内容数据的划分 以下是我存储的…