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

哈希深渊
• 阅读 132

**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喔

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


  // 定义日志标识符
  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
    }
  }
}
点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
4年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Wesley13 Wesley13
4年前
VBox 启动虚拟机失败
在Vbox(5.0.8版本)启动Ubuntu的虚拟机时,遇到错误信息:NtCreateFile(\\Device\\VBoxDrvStub)failed:0xc000000034STATUS\_OBJECT\_NAME\_NOT\_FOUND(0retries) (rc101)Makesurethekern
Wesley13 Wesley13
4年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Stella981 Stella981
4年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
4年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
4年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Easter79 Easter79
4年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
4年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Python进阶者 Python进阶者
2年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
哈希深渊
哈希深渊
Lv1
墙里秋千墙外道。墙外行人,墙里佳人笑。笑渐不闻声渐悄,多情却被无情恼。
文章
4
粉丝
0
获赞
0