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

news/2024/10/5 8:14:27/
http://www.w3.org/2000/svg" style="display: none;">

在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.ppmy.cn/news/1534846.html

相关文章

微信小程序数据操作指南:从绑定到更新

微信小程序数据操作指南:从绑定到更新 在微信小程序开发中,数据操作是核心环节之一。微信小程序提供了一系列简洁而强大的数据操作方法,帮助开发者轻松实现数据的绑定、更新和渲染。本文将详细介绍微信小程序中常用的数据操作方法&#xff0…

数据结构阶段测试2--(试题解析)

数据结构阶段测试2–(试题解析) 选择题 将⻓度为n的单链表连接在⻓度为m的单链表之后,其算法的时间复杂度为() A. O(m) B. O(1) C. O(n) D. O(mn) 解析思路 链表的尾插操作 💡 答案:A 单链表由于需要找到最后⼀个⾮空节点…

WebGL在低配置电脑的应用

在低配置电脑上实现WebGL渲染,需要采取一系列优化策略来减轻硬件负担,提升渲染性能。以下是一些详细的实现方法: 1. 优化WebGL代码和设置 a. 减少绘制调用次数 通过合并绘制操作、使用批量绘制等方式,尽量减少绘制调用次数。这可以…

c#中的功能优势

装箱和拆箱 性能消耗的直接体现 int iterations 10000000; // 进行一千万次迭代Stopwatch stopwatch new Stopwatch();// 非装箱测试stopwatch.Start();for (int i 0; i < iterations; i){int x i; // 纯值类型操作&#xff0c;无装箱}stopwatch.Stop();Console.Writ…

Chromium 硬件加速开关c++

选项页控制硬件加速开关 1、前端代码 <settings-toggle-button id"hardwareAcceleration"pref"{{prefs.hardware_acceleration_mode.enabled}}"label"$i18n{hardwareAccelerationLabel}"><template is"dom-if" if"[…

BugReport中的App Processor wakeup字段意义

一、功耗字段意义&#xff1a; App processor wakeup:Netd基于xt_idletimer 待机下监视网络设备的收发工作状态&#xff0c;即当设备发生联网从休眠态变成为唤醒态时&#xff0c;会记录打醒者的uid(uid大于0)和网络类型(wifi或数据类型)、时间戳 实际日志&#xff1a;我们在B…

基于MATLAB的安全帽检测系统

课题名称 课题介绍 众所周知&#xff0c;在一些施工工地&#xff0c;必须明确佩戴安全帽。可以对生命安全起到保障作用。该课题为常见的安全帽的识别&#xff0c;主要分为红色&#xff0c;蓝色&#xff0c;黄色三类安全帽。而安全帽的主要是红色&#xff0c;蓝色&…

UFS 3.1架构简介

整个UFS协议栈可以分为三层:应用层(UFS Application Layer(UAP)),传输层(UFS Transport Layer(UTP)),链路层(UIC InterConnect Layer(UIC))。应用层发出SCSI命令(UFS没有自己的命令使用的是简化的SCSI命令),在传输层将SCSI分装为UPIU,再经过链路层将命令发送给Devices。下…