当前位置: 首页 > news >正文

[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;
}

http://www.xdnf.cn/news/581257.html

相关文章:

  • 【FAQ】HarmonyOS SDK 闭源开放能力 —Live View Kit (3)
  • HarmonyOS NEXT~React Native 在鸿蒙系统上的应用与实践
  • 企业网站架构部署与优化第4章Nginx核心功能
  • Axios中POST、PUT、PATCH用法区别
  • 服务器硬盘分类
  • 小白的进阶之路系列之三----人工智能从初步到精通pytorch计算机视觉详解下
  • C# 使用 Source Generation 提升 System.Text.Json 性能
  • 职坐标嵌入式MCU/DSP与RTOS开发精讲
  • Android logcat命令汇总
  • Elasticsearch 写入性能优化有哪些常见手段?
  • c++11特性——lambda对象、包装器
  • Strands Agents:AWS开源Agent框架的技术与应用全景
  • MySQL 索引失效及其解决办法
  • 全面学习c++类与对象(中)(非常重要)(析构构造拷贝函数赋值运算符重载等等)
  • 养生攻略:五步打造健康生活
  • Three.js搭建小米SU7三维汽车实战(1)搭建开发环境
  • 腾讯云媒体AI解码全球视频出海智能密码
  • 替代云数据库的本地方案:MySQL+phpMyAdmin的远程管理与跨网络访问技术
  • Windows下PyCharm2025的运行卡顿的问题
  • 介绍一下 MVCC
  • 2025最新版Visual Studio Code for Mac安装使用指南
  • Spark入门秘籍
  • Docker 疑难杂症解决指南大纲
  • 人民日报社主管媒体深度聚焦珈和科技“遥感+AI”农险精准化突破:首创“四维数据贯通”模式 树行业转型新标杆
  • RNN神经网络
  • tmagic-editor本地实践(2)
  • 当物联网“芯”闯入纳米世界:ESP32-S3驱动的原子力显微镜能走多远?
  • centos8 配置网桥,并禁止kvm默认网桥
  • WPF 常见坑:ContentControl 不绑定 Content 时,命令为何失效?
  • 使用 Selenium 自动化测试:保存网站登录数据的详细指南