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

在 ArkTS 网络请求中,重新封装一下 http 模块

在ArkTS中,重新封装http模块可以提供一个更简洁、更易于使用的API,同时隐藏底层细节,使开发者能够更专注于业务逻辑。以下是一个简单的示例,展示了如何重新封装鸿蒙系统的@kit.NetworkKit中的http模块:

// 创建一个新的文件,例如 httpService.etsimport http from '@ohos.net.http';import { http } from "@kit.NetworkKit";
import CommonConstant from "../constants/Contants";
import {AllType} from "./Type"export class HttpService {private static instance: HttpService;// 私有构造函数,防止外部实例化private constructor() {}// 获取单例public static getInstance(): HttpService {if (!HttpService.instance) {HttpService.instance = new HttpService();}return HttpService.instance;}// 发起GET请求public async get(url: string, headers?: object) {const httpRequest = http.createHttp();try {const response = await httpRequest.request(url, {method: http.RequestMethod.GET,header: headers,readTimeout: CommonConstant.READ_TIMEOUT,connectTimeout: CommonConstant.CONNECT_TIMEOUT});if (response.responseCode === 200) {return response.result;} else {throw new Error(`请求失败: ${response.responseCode}`);}} catch (error) {throw new Error(`请求发生错误: ${error.message}`);}}// 发起POST请求public async post(url: string, params:AllType, headers?: object) {const httpRequest = http.createHttp();try {const response = await httpRequest.request(url,{method: http.RequestMethod.POST,header: {'Content-Type': 'application/json'},extraData: params,readTimeout: CommonConstant.READ_TIMEOUT,connectTimeout: CommonConstant.CONNECT_TIMEOUT});if (response.responseCode === 200) {return JSON.stringify(response.result);} else {throw new Error(`请求失败: ${response.responseCode}`);}} catch (error) {throw new Error(`请求发生错误: ${error.message}`);}}
}
;

使用示例:

// 使用示例
// 在你的组件或服务中
import {HttpService } from "../common/utils/HttpUtils";
const httpService = HttpService.getInstance();httpService.get('https://api.example.com/data').then(response => {console.log('请求成功:', response);}).catch(error => {console.error('请求失败:', error);});httpService.post('https://api.example.com/submit', { key: 'value' }).then(response => {console.log('提交成功:', response);}).catch(error => {console.error('提交失败:', error);});

在这个封装中,我们创建了一个HttpService类,它使用单例模式来确保全局只有一个实例。这个类提供了getpost方法,分别用于发起GET和POST请求。你可以根据需要添加其他HTTP方法,如PUT、DELETE等。

注意,这个封装假设服务器返回的是JSON格式的数据,并在成功响应时将其解析为JavaScript对象。如果服务器返回的是其他格式的数据,你需要相应地修改解析逻辑。

此外,这个封装没有处理请求超时、重试机制等高级功能。如果你需要这些功能,可以在封装中添加相应的逻辑。

最后,请确保在项目的config.jsonmodule.json5文件中正确配置了网络权限,以便应用能够访问网络。

http://www.lryc.cn/news/455393.html

相关文章:

  • Microsoft 更新 Copilot AI,未來將能使用語音並看到你瀏覽的網頁
  • 系统架构设计师-论文题(2021年下半年)
  • selenium的webdriver常用方法和属性介绍(2)
  • 73.【C语言】C/C++的内存区域划分
  • k8s 中存储之 hostPath 卷
  • Cherno游戏引擎笔记(73~90)
  • helm 测试卸载或删除(redis)
  • 关于Qt音乐播放器进度条拖拽无用的问题解决方案
  • Redis:初识Redis
  • 【React】增量传输与渲染
  • 【回眸】Tessy 单元测试软件使用指南(四)常见报错及解决方案与批量初始化的经验
  • 2024 - 10 :生物药学: 如何获取对应核心靶点基因的激酶
  • STM32 HAL库UART查询方式实例
  • 数据结构--线性表双向链表的实现
  • 第一个Flutter应用(一)
  • 批量查询快递单号物流信息:高效掌握最后更新动态
  • 随着硬件水平的提升,LabVIEW有哪些过去的编程方法被淘汰掉了
  • Leetcode 206.反转链表
  • 基于springboot和vue.js 养老院管理系统设计与实现
  • 高效数据处理:MapReduce与Hive的实战应用
  • 【含开题报告+文档+PPT+源码】基于springboot的迎新系统
  • C#-委托delegate
  • 编译Thingsboard3.7.0的过程记录
  • vulnhub-THE PLANETS-EARTH靶机
  • 【C语言】分支和循环(2)
  • Python数据分析-远程办公与心理健康分析
  • LabVIEW提高开发效率技巧----使用动态事件
  • 【STM32开发之寄存器版】(五)-窗口看门狗WWDG
  • Leetcode203.移除链表元素-Python
  • 属性拷贝MapStruct