当前位置:   article > 正文

鸿蒙OS ArkUI 封装接口网络请求 -- 小白篇_鸿蒙axios封装

鸿蒙axios封装

鸿蒙OS ArkUI 封装接口网络请求 – 小白篇

根据官方文档自己又稍微改了一部分,因为写法还比较不太习惯可能封装的比较简陋,但是能用。
后边如果对技术了解更多的话可能会再出一篇进阶的然后增加点修改

首先的思路是要创建一个http的访问,下边是 代码片

HttpUtil.ets

import http from '@ohos.net.http'; //引入官方提供的http请求包
//下边这个引用是自定义了一些返回体和状态的代码
import { CommonConstants as Const, ContentType,ResponseResult } from '../common/constants/CommonConstants';';

/**
 * @param url 接口请求地址 例如/login
 * @param method 请求类型 
 * @param params 参数 (可选项)
 */
 
export function httpRequest(url: string,method:http.RequestMethod,params?:any): Promise<ResponseResult> {
	//创建一个请求
  let httpRequest = http.createHttp();
  //拼接请求接口地址
  //Const.SERVER 这个是被抽离出去的你的http:xxx.com地址
  let responseResult = httpRequest.request(`${Const.SERVER}`+url, {
    method: method,// 请求方式 get post delete put 这个需要自己去做
    readTimeout: Const.HTTP_READ_TIMEOUT,
    header: {
      'Content-Type': ContentType.JSON // 请求头
    },
    connectTimeout: Const.HTTP_READ_TIMEOUT, 
    //  如果是POST请求就可以直接传第三个参数 如果是get 那就需要在URL传递进来前拼接好
    //  ps:我没想好get怎么封装
    extraData: params  
  });
  let serverData: ResponseResult = new ResponseResult();
  // 处理返回数据 下边可以根据自己业务逻辑自己处理
  return responseResult.then((value: http.HttpResponse) => {
    if (value.responseCode === Const.HTTP_CODE_200) {
      let result = `${value.result}`;
      let resultJson: ResponseResult = JSON.parse(result);
      if (resultJson.code === Const.SERVER_CODE_SUCCESS) {
        serverData.data = resultJson.data;
      }
      serverData.code = resultJson.code;
      serverData.msg = resultJson.msg;
    } else {
      serverData.msg = `Network request failed, please try later!&${value.responseCode}`;
    }
    return serverData;
  }).catch(() => {
    serverData.msg = 'Network request failed, please try later!';
    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
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

CommonConstants.ets

export class CommonConstants {
  static readonly SERVER: string = 'http://xxx:8888';
  static readonly POST_LOGIN: string = '/login';
  /**
   * 接口返回状态码
   */
  static readonly SERVER_CODE_SUCCESS: number = 0;
  /**
   * 请求成功状态码
   */
  static readonly HTTP_CODE_200: number = 200;

  /**
   * 超时时间
   */
  static readonly HTTP_READ_TIMEOUT: number = 10000;

}

/**
 * 请求头
 */
export const enum ContentType {
  JSON = 'application/json'
}


/**
 * 请求类型
 */
export enum RequestMethod {
  OPTIONS = "OPTIONS",
  GET = "GET",
  HEAD = "HEAD",
  POST = "POST",
  PUT = "PUT",
  DELETE = "DELETE",
  TRACE = "TRACE",
  CONNECT = "CONNECT"
}

/**
 * 请求返回体
 */

export class ResponseResult {
  code: number;
  msg: string | Resource;
  data: any;
  constructor() {
    this.code = 10086;
    this.msg = '';
    this.data = '';
  }
}
  • 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
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

实际使用

//引入你定义好的方法和返回
import {CommonConstants as Const,ResponseResult,RequestMethod} from '../common/constants/CommonConstants';
import { httpRequest } from '../Utils/HttpUtil';


Login():void {//例如登录接口 POST请求
	httpRequest(Const.POST_LOGIN,RequestMethod.POST,{'account':'你的账号','password':'你的密码'}).then((data: ResponseResult) => {
	   if (data.code === Const.SERVER_CODE_SUCCESS) {
	     Logger.error('rescueLogin failed', data.data);
	     // resolve(data.data);
	   } else {
	     Logger.info('rescueLogin errorcode', JSON.stringify(data));
	   }
	 }).catch((err: Error) => {
	   Logger.error('rescueLogin catch', JSON.stringify(err));
	 });
	 
	//例如登录接口 GET请求
	let url:string = Const.POST_LOGIN+`?account=${this.account}&password=${this.password}`
	httpRequest(url,RequestMethod.GET).then((data: ResponseResult) => {
	   if (data.code === Const.SERVER_CODE_SUCCESS) {
	     Logger.error('rescueLogin failed', data.data);
	     // resolve(data.data);
	   } else {
	     Logger.info('rescueLogin errorcode', JSON.stringify(data));
	   }
	 }).catch((err: Error) => {
	   Logger.error('rescueLogin catch', JSON.stringify(err));
	 });
}
  • 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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/231907
推荐阅读
相关标签
  

闽ICP备14008679号