【HarmonyOS Arkts笔记】http网络请求封装

common.ts

typescript 复制代码
export default class CommonConstant {
  /**
   * The host address of the server.
   */
  static readonly SERVER: string = '请求接口地址';

  /**
   * The request success code.
   */
  static readonly SUCCESS_CODE: number = 200;

  /**
   * Read timeout.
   */
  static readonly READ_TIMEOUT: number = 50000;

  /**
   * Connect timeout.
   */
  static readonly CONNECT_TIMEOUT: number = 50000;
}

request.ts

typescript 复制代码
import http from '@ohos.net.http';
import CommonConstant from './common';
import Prompt from '@system.prompt';

const request = (url: string, data?: Object, header?: Object,) => {
  return new Promise((resolve, reject) => {
    // 请求头
    let h
    if (header) {
      h = header
    } else {
      h = {
        'Content-Type': 'application/json',
      }
    }

    // 每一个httpRequest对应一个HTTP请求任务,不可复用
    let httpRequest = http.createHttp();

    // 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
    // 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
    httpRequest.on('headersReceive', (header) => {
      // console.info('header: ' + JSON.stringify(header));
    });

    httpRequest.request(
      // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
      CommonConstant.SERVER + url,
      {
        method: http.RequestMethod.POST,
        // 开发者根据自身业务需要添加header字段
        header: h,
        // 当使用POST请求时此字段用于传递内容
        extraData: data,
        expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
        usingCache: true, // 可选,默认为true
        priority: 1, // 可选,默认为1
        connectTimeout: 60000, // 可选,默认为60000ms
        readTimeout: 60000, // 可选,默认为60000ms
      }, (err, res: any) => {
      if (!err) {
        // data.result为HTTP响应内容,可根据业务需要进行解析
        console.info('Result:' + res.result);
        resolve(JSON.parse(res.result))
      } else {
        console.info('error:' + JSON.stringify(err));
        Prompt.showToast({
          message: JSON.stringify(err)
        })
        return JSON.stringify(err)
        // reject(JSON.stringify(err))
        // 取消订阅HTTP响应头事件
        httpRequest.off('headersReceive');
        // 当该请求使用完毕时,调用destroy方法主动销毁。
        httpRequest.destroy();
      }
    });
  })
}

export default request

接口汇总

typescript 复制代码
import request from "./request"

const loginApi = {
  // 账号登录
  async login(data: object) {
    return await request('/account/login', data, {Token: false})
  }
}

export default loginApi

页面调用

typescript 复制代码
import loginApi from "../../api/login"

loginApi.login({
      account: this.account,
      password: this.password
    }).then((res: any) => {
      if (res.code == 1) {
        console.info(res.data)
      }
    })
相关推荐
Goodbye4 天前
大模型无状态架构:从 HTTP 协议到 Harness AI 工程的深度解析
http
LinXunFeng7 天前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
霜落长河10 天前
抛弃TCP改用UDP,HTTP3怎么了?
http
网络研究院11 天前
2026年网络安全
网络·安全·法律·法规·趋势·发展
酣大智11 天前
ARP代理--工作原理
运维·网络·arp·arp代理
treesforest11 天前
AI安全系统如何识别异常访问?IP风险识别正在成为关键能力
网络·人工智能·tcp/ip·安全·web安全
shushangyun_11 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
闪闪发亮的小星星11 天前
高斯光以及高斯光公式解释
笔记
2601_9618451511 天前
粉笔行测题库|系统班|刷题
网络·百度·微信·微信公众平台·facebook·新浪微博
程序猿阿伟11 天前
《Chrome离线扩展安装的底层逻辑与场景落地指南》
服务器·网络·chrome