当前位置:   article > 正文

HarmonyOS NEXT API12关于axios的网络封装_harmonyos next axios

harmonyos next axios

1.开发工具

DeEco Studio NEXT Developer Bate1

2.API版本

12

3.开发过程

安装axios

OpenHarmony三方库中心仓:https://ohpm.openharmony.cn/#/cn/home

项目中执行

ohpm install @ohos/axios
  • 1

主体业务实现(因实际业务api的返回值不是固定的所以未封装code判断到Util里面,可根据个人情况进行改造)HttpUtil.ets

import axios, { AxiosResponse } from '@ohos/axios';
import ResponseResult from '../common/bean/ResponseResult';
import { http } from '@kit.NetworkKit';
import { Apis } from './Apis';
import Logger from './Logger';

const TAG = '[HttpUtil]';

export class HttpUtil {
  public static  request(url: string, params: ESObject = {}, method = http.RequestMethod.GET,
    contentType?: string): Promise<ResponseResult> {
    axios.defaults.headers['Content-Type'] =
      contentType || method === http.RequestMethod.POST ? 'application/json' : 'application/x-www-form-urlencoded';
    let responseResult:Promise<AxiosResponse<string>>  =  axios.request({
      url,
      method,
      params
    });
    let serverData: ResponseResult = new ResponseResult();
    return responseResult.then((response: AxiosResponse<string>)=>{
      Logger.info(TAG, "网络请求:" + "接口:" + Apis.BASE_Url + url + " 参数: " + JSON.stringify(params) + "返回结果:" + JSON.stringify(response.data));
      if (response.status == http.ResponseCode.OK) {
        serverData = JSON.parse(JSON.stringify(response.data));
      } else {
        serverData.resCode = Apis.BASE_ERROR_CODE;
        serverData.resMsg = `${'网络错误,请联系管理员:'}&${response.status}`;
      }
      return serverData;
    }).catch((e:object) => {
      Logger.info(TAG,"网络请求异常:"+ JSON.stringify(e))
      serverData.resCode = Apis.BASE_ERROR_CODE;
      serverData.resMsg = '网络错误,请联系管理员';
      return serverData;
    })
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

业务调用HomeViewModel.ets(获取banner)

import BannerBean from '../common/bean/BannerBean';
import ResponseResult from '../common/bean/ResponseResult';
import { Apis } from '../utils/Apis';
import { HttpUtil } from '../utils/HttpUtil';


export class HomeViewModel {
  getBannerList(): Promise<BannerBean[]> {
    return new Promise((resolve: Function, reject: Function) => {
      HttpUtil.request(Apis.BASE_Url+Apis.bannerList).then((res: ResponseResult) => {
        if (res.resCode == 1) {
          resolve(res.data);
        } else {
          reject(res.resMsg);
        }
      }).catch((res:object) => {
        reject(JSON.stringify(res));
      });
    });
  }
}
export default new HomeViewModel();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

ResponseResult.ets

export default class ResponseResult {
  resCode: number |string;
  resMsg: string | Resource;
  data: string | Object | ArrayBuffer | null;

  constructor() {
    this.resCode = 0;
    this.resMsg = '';
    this.data = null;
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Logger.ets

import { hilog } from '@kit.PerformanceAnalysisKit';

export class Logger {
  private domain: number;
  private prefix: string;
  private format: string = `%{public}s, %{public}s`;

  constructor(prefix: string) {
    this.prefix = prefix;
    this.domain = 0xFF00;
  }

  debug(...args: string[]) {
    hilog.debug(this.domain, this.prefix, this.format, args);
  }

  info(...args: string[]) {
    hilog.info(this.domain, this.prefix, this.format, args);
  }

  warn(...args: string[]) {
    hilog.warn(this.domain, this.prefix, this.format, args);
  }

  error(...args: string[]) {
    hilog.error(this.domain, this.prefix, this.format, args);
  }

  fatal(...args: string[]) {
    hilog.fatal(this.domain, this.prefix, this.format, args);
  }

  isLoggable(level: number) {
    hilog.isLoggable(this.domain, this.prefix, level);
  }
}

export default new Logger('[WoNiu]');
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/878298
推荐阅读
相关标签
  

闽ICP备14008679号