鸿蒙OS开发实例:【工具类封装-http请求】

电子说

1.2w人已加入

描述

import http from '@ohos.net.http';
import promptAction from '@ohos.promptAction';

封装HTTP接口请求类,提供格式化的响应信息输出功能。
使用 DevEco Studio 3.1.1 Release 及以上版本,API 版本为 api 9 及以上。

示例:

import { MyHttpUtil } from '../common/utils/MyHttpUtil';
 async function fetchWeatherData() {
 const request = await MyHttpUtil.request('https://api.oioweb.cn/api/weather/GetWeather', 'GET', {}, true);
 }
鸿蒙OS开发更多内容↓点击HarmonyOS与OpenHarmony技术
鸿蒙技术文档开发知识更新库gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md在这。或+mau123789学习,是v喔

OpenHarmony

// 定义日志标识符
  private static readonly LOG_TAG: string = "====MyHttpUtil";

  /**
   * 发起HTTP请求的方法封装.
   * @param url API 地址,若不包含协议头,则自动添加当前应用的主机域名。
   * @param method 请求方法,如 'GET', 'POST' 等。
   * @param params 当HTTP请求方法为GET、OPTIONS、DELETE、TRACE、CONNECT时,此参数用于传递查询字符串;对于POST方法,这些数据会被作为请求体内容。
   * @param showErrorToast 若为 true,在接口业务错误时,向用户显示 toast 提示信息。
   * @returns 成功时返回接口响应数据,请求异常时返回 undefined。
   */
  public static async request(url: string, method: string, extraData: object, showErrorToast: boolean): Promise< any | undefined > {
    try {
      if (!url) {
        return undefined;
      }
      console.info(`${MyHttpUtil.LOG_TAG}: Request started with URL:`, url);

      let request = http.createHttp();
      let options = {
        method: method, //http.RequestMethod.GET 或 http.RequestMethod.POST
        header: {
          'Content-Type': 'application/json'
        },
        readTimeout: 50000, //读取超时时间。单位为毫秒(ms),默认为60000ms。 设置为0表示不会出现超时情况。
        connectTimeout: 50000, //连接超时时间。单位为毫秒(ms),默认为60000ms。
        extraData: extraData,
      } as http.HttpRequestOptions;
      let result = await request.request(url, options);
      result = JSON.parse(JSON.stringify(result))

      console.info(MyHttpUtil.LOG_TAG, 'request end url:', url); //请求结束后
      console.info(MyHttpUtil.LOG_TAG, 'request method:', method);
      console.info(MyHttpUtil.LOG_TAG, 'request extraData:', JSON.stringify(extraData));
      // console.info(MyHttpUtil.LOG, 'request result', JSON.stringify(result, null, 2));
      console.info(MyHttpUtil.LOG_TAG, 'request result', JSON.stringify(result));
      if (result.responseCode == 200) {
        console.info(MyHttpUtil.LOG_TAG, 'request code 200 result', result.result.toString());
        console.info(MyHttpUtil.LOG_TAG, 'request code 200 result', JSON.stringify(JSON.parse(result.result.toString()), null, 2));
        // console.info(MyHttpUtil.LOG, 'request code 200 result',  JSON.parse(result.result.toString()));
      }

      //判断业务异常时,弹出对应的toast
      if (showErrorToast) { //TODO 还需要追加自己业务的判断
        promptAction.showToast({
          message: '这里打印接口业务的message错误信息,根据自己公司接口业务情况封装。',
          duration: 2000,
          bottom: '375lpx'
        })
      }
      return result;
    } catch (error) {
      console.error(MyHttpUtil.LOG_TAG, 'request end url:', url);
      console.error(MyHttpUtil.LOG_TAG, 'request method:', method);
      console.error(MyHttpUtil.LOG_TAG, 'request extraData:', JSON.stringify(extraData));
      console.error(MyHttpUtil.LOG_TAG, 'request', JSON.stringify(error));
    } finally {
      return undefined
    }
  }
}
}

审核编辑 黄宇

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分