[Harmony]网络请求
1.导入@ohos/axios
安装依赖
通过OHPM(OpenHarmony包管理器)安装:
ohpm install @ohos/axios
安装后需在oh-package.json5
中确认版本号。
权限配置
在module.json5
中添加网络权限,允许应用访问互联网。
"requestPermissions": [{"name": "ohos.permission.INTERNET", // 网络权限"reason": "$string:internet_reason","usedScene": {"abilities": [],"when": "always"}}],
2.对axios再次封装
/*** HTTP请求服务封装类* 基于@ohos/axios封装GET/POST请求* 提供统一的错误处理和请求配置*/
import axios, { AxiosRequestConfig, AxiosResponse } from '@ohos/axios';
import { CurrentEnvironmentType, MFGlobalConfig } from '../../config/MFGlobalConfig';export enum ServerBaseURLType {base6600, // 默认0base6610, // 自动递增为1
}// 响应数据结构定义
export interface HttpResponseData {Code: number;Msg: string;RetData?: object;
}class HttpService {// Axios实例配置private instance = axios.create({//baseURL: 'https://test.com', // 基础API地址timeout: 20000, // 请求超时时间(20秒)headers: { // 默认请求头'Content-Type': 'application/json','X-Platform': 'HarmonyOS'}});// 域名private domain(type: ServerBaseURLType): string {if (MFGlobalConfig.currentEnv == CurrentEnvironmentType.dev) { // 测试环境if (type == ServerBaseURLType.base6600) {return "http://116.205.195.310:6600"} else if (type == ServerBaseURLType.base6610) {return "http://116.205.195.410:6610"} else {return "http://116.205.195.410:6600"}} else { // 正式环境if (type == ServerBaseURLType.base6600) {return "http://base.pro.com"} else if (type == ServerBaseURLType.base6610) {return "http://busi.pro.com"} else {return "http://base.pro.com"}}}/*** 每次请求必须请求 用来更新instance* 设置基础URL和header* @param serverType 服务器类型枚举*/private updateInstance(serverType: ServerBaseURLType, params?: object): void {// 修改基础API地址this.instance.defaults.baseURL = this.domain(serverType) + '/api';// 重置headerthis.instance.defaults.headers['Token'] = ''; // 添加/修改单个headerthis.instance.defaults.headers['TimeStamp'] = '';this.instance.defaults.headers['Sign'] = '';this.instance.defaults.headers['Version'] = '';// 更新Header}/*** 配置公共参数* get请求不用传太多公共参数*/private commonParams(params: Record<string, number | String>) : Record<string, number | String> {// 获取键名数组let keys = Object.keys(params)let haveSayId = keys.includes('SysId')if (!haveSayId) {params['SysId'] = '1000'}let haveSourceType = keys.includes('SourceType')if (!haveSourceType) {params['SourceType'] = 3}let haveOrgId = keys.includes('OrgId')if (!haveOrgId) {//params['OrgId'] = '' }return params;}/*** GET请求方法* @param path 请求路径(相对baseURL)* @param params 查询参数对象* @param serverType 基础API地址类型* @returns Promise<T> 返回指定类型的响应数据*/async get<T>(path: string, params?: Record<string, number | String>, serverType: ServerBaseURLType = ServerBaseURLType.base6610): Promise<T> {if (params != null) {params = this.commonParams(params);}this.updateInstance(serverType, params);const config: AxiosRequestConfig = {method: 'GET',url: path,params: params};return this.executeRequest<T>(config);}/*** POST请求方法* @param path 请求路径* @param data 请求体数据* @param serverType 基础API地址类型* @returns Promise<T> 返回指定类型的响应数据*/async post<T>(path: string, data: Record<string, number | String>, serverType: ServerBaseURLType = ServerBaseURLType.base6610): Promise<T> {data = this.commonParams(data);this.updateInstance(serverType, data);const config: AxiosRequestConfig = {method: 'POST',url: path,data: data};return this.executeRequest<T>(config);}/*** 统一请求执行方法* @param config 请求配置对象* @throws 标准化错误对象* @returns Promise<T> 响应数据*/private async executeRequest<T>(config: AxiosRequestConfig): Promise<T> {try {const response: AxiosResponse<T> = await this.instance.request(config);return response.data;} catch (error) {console.error(`请求失败 [${config.method} ${config.url}]:`, error);// 错误分类处理if (error.response) {throw new Error(`服务端异常: ${error.response.status}`);} else if (error.request) {throw new Error('网络连接异常');} else {throw new Error('请求配置错误');}}}
}// 导出单例实例
export const httpReq = new HttpService();
3.使用示例
async loginAction() {let par = {'Phone':this.userPhone, 'Password': this.password} as Record<string, number | String>;httpReq.post<HttpResponseData>('/Person/Login', par).then(resData => {if (resData.Code == 200) {console.log('登录成功');} else {console.log('登录失败');}}).catch((error: Error) => {ConsoleLog.error('登录失败:', error.message);Toast.show(error.message)});
}// 登录响应数据结构定义
interface LoginResponse {Token: string; // 认证令牌Phone: string;OrgName: number;
}