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

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

typescript 复制代码
// 创建一个新的文件,例如 httpService.ets

import 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}`);
    }
  }
}
;

使用示例:

typescript 复制代码
// 使用示例
// 在你的组件或服务中
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文件中正确配置了网络权限,以便应用能够访问网络。

相关推荐
WinyQ01 分钟前
【DeepStream】整合出现的问题
linux·运维·网络
小魏每天都学习6 分钟前
【网络拓扑部署-网络设备-网络安全】
运维·网络
zd8451015006 分钟前
CubeMX H743 lwip ETH初始化流程
网络·stm32·单片机
zzh_my10 分钟前
tcp 服务端(用于测试)
服务器·网络·tcp/ip
SmartRadio15 分钟前
LLCC68 L型与π型匹配网络的调试方法
网络·lora·阻抗匹配·匹配·射频·llcc68
资深web全栈开发18 分钟前
QUIC 协议:为什么谷歌要用 UDP 重做一遍 TCP?
网络协议·tcp/ip·udp
橙露23 分钟前
工业控制嵌入式开发:Modbus 协议在 STM32 中的实现与调试
服务器·网络·stm32
jiecy25 分钟前
基础问题:1.1.1.2/24 和 1.1.1.2/22 是同一个 IP 吗?
网络·网络协议·tcp/ip
孟无岐29 分钟前
【Laya】HttpRequest 网络请求
网络·typescript·游戏引擎·游戏程序·laya
游戏开发爱好者842 分钟前
iPhone 网络调试的过程,请求是否发出,是否经过系统代理,app 绕过代理获取数据
android·网络·ios·小程序·uni-app·iphone·webview