【鸿蒙实战开发教程】HarmonyOS next开发网络哀求封装(Api11Release) ...

打印 上一主题 下一主题

主题 531|帖子 531|积分 1593

前言

   根据研究机构Counterpoint Research发布的最新数据,2024年第一季度,鸿蒙OS份额由客岁一季度的8%上涨至17%,iOS份额则从20%下降至16%。 这意味着,华为鸿蒙OS在中国市场的份额超越苹果iOS,已成中国第二大操作系统。

  随着鸿蒙市场份额的不停提升,相应的岗位也会迎来一个爆发式的增长。这对于想要换赛道的程序员来说是一个非常好的消息,话说各人近来有想法转型鸿蒙开发吗?

本文主要讲一下鸿蒙开发中网络哀求封装
鸿蒙相干版本信息:

HarmonyOS NEXT,Developer Preview2,Api Version 11 Release
电脑系统:macM1 编译器:DevEco Studio NEXT Developer Preview2,4.1.7.300
(API9对应的mac版本的模仿器无法识别的题目在此版本编译器已经修复)
模仿器也是一样的Preview2版本(需要申请)
近来开始基于鸿蒙NEXT版本也就是俗话说的纯血鸿蒙举行开发,本来是不打算写这个文章因为用API9写的时候其时是封装了一套网络哀求的,但是~API 11改了一些地方: any 被禁止使用了(这是影响最大的地方其他的改变也造成了一些影响但是我就不外多形貌了),然后就导致报错严重!!

下面就开始进入主题:
起首在module.json5中配置基础网络权限

  1. "requestPermissions": [
  2.     {
  3.       "name": "ohos.permission.INTERNET",
  4.     }
  5. ]
复制代码
定义base常量

我这里base地址使用的wan安卓的api

封装泛型工具类


留意data,不能像之前那样
  1. data: T = null
复制代码
会报错,而且必须都有初始值
封装request

  1. async function requestSync<T>(path: string, method: http.RequestMethod, extraData?: Object): Promise<Response<T>> {
  2.   return new Promise<Response<T>>((resolve, reject) => {
  3.     let url = NetConstants.BASE_URL + path;
  4.     let header: HeaderInterFace = {
  5.       ApiVersion: '272',
  6.       'Content-Type': 'application/json',
  7.       platform: '',
  8.       'encryption-mode': 'base64',
  9.       auth: NetConstants.AUTH,
  10.       channel: 'JYB',
  11.       timeout : NetConstants.TIMEOUT
  12.     }
  13.     if (method === http.RequestMethod.POST) {
  14.       header = {
  15.         ApiVersion: '272',
  16.         'Content-Type': 'application/x-www-form-urlencoded',
  17.         platform: '',
  18.         'encryption-mode': 'base64',
  19.         auth: NetConstants.AUTH,
  20.         channel: 'JYB',
  21.         timeout : NetConstants.TIMEOUT
  22.       }
  23.     }
  24.     let httpRequest = http.createHttp();
  25.     hilog.info(0, NetConstants.NET_TAG, `start request, path: ${path}, method: ${method}, extraData: ` + JSON.stringify(extraData));
  26.     httpRequest.request(
  27.       url,
  28.       {
  29.         method: method,
  30.         expectDataType: http.HttpDataType.OBJECT,
  31.         header: header,
  32.         extraData: extraData
  33.       },
  34.       (err, data) => {
  35.         let res = new Response<T>()
  36.         if (!err && data.responseCode === 200) {
  37.           //Object.assign("", "");对象合并
  38.           if (typeof data.result === 'string') {
  39.             res.data = JSON.parse(data.result)
  40.           } else {
  41.             // Object.assign(res, data.result);
  42.             res.data = data.result as T
  43.           }
  44.           hilog.info(0, NetConstants.NET_TAG, `request success, path: ${path}, result: ${JSON.stringify(res)}`)
  45.         } else {
  46.           hilog.error(0, NetConstants.NET_TAG, `request error, path: ${path}, error: ${JSON.stringify(err)}`)
  47.           res.errorCode = data?.responseCode??-1
  48.           res.errorMsg = err?.message??""
  49.         }
  50.         resolve(res);
  51.       }
  52.     )
  53.   })
  54. }
  55. //封装接口
  56. export default class Api {
  57.   private static instance: Api;
  58.   private constructor() {
  59.   }
  60.   static net(): Api {
  61.     if (Api.instance === undefined) {
  62.       Api.instance = new Api();
  63.     }
  64.     return Api.instance;
  65.   }
  66.   async login(username: string, password: string): Promise<Response<UserData>> {
  67.     return requestSync("/user/login", http.RequestMethod.POST, `username=${username}&password=${password}`);
  68.   }
  69.   async logout(): Promise<Response<string>> {
  70.     return requestSync("/user/logout/json", http.RequestMethod.GET);
  71.   }
  72.   async getUserInfo(): Promise<Response<UserData>> {
  73.     return requestSync("/lg/coin/userinfo/json", http.RequestMethod.GET);
  74.   }
  75. }
  76. interface HeaderInterFace {
  77.   'ApiVersion': string,
  78.   'Content-Type': string,
  79.   'platform': string,
  80.   'encryption-mode': string,
  81.   'auth': string,
  82.   'channel': string,
  83.   'timeout': number
  84. }
复制代码
我这里没有编写处理惩罚token和加密加密相干的,这两个实在也不复杂,各人可以本身添加。
我这里只写了三个接口,但是实在相称于只有一个post哀求一个get哀求,假如需要delete、put哀求本身添加。
试一下:
一个简单的登岸页:
  1. @Entry
  2. @Component
  3. export struct Login {
  4.   @State showLoading: boolean = false;
  5.   @State title: string = "登录";
  6.   private account: string = "";
  7.   private password: string = "";
  8.   async login(){
  9.     if (!this.account) {
  10.       toast("请输入用户名");
  11.       return;
  12.     }
  13.     if (!this.password) {
  14.       toast("请输入密码");
  15.       return;
  16.     }
  17.     this.showLoading = true;
  18.     let res = await Api.net().login(this.account, this.password);
  19.     this.showLoading = false;
  20.     if (res.isSuccessWithData()) {
  21.       toast("登录成功");
  22.     } else {
  23.       toast(res.errorMsg);
  24.     }
  25.   }
  26.   build() {
  27.     Stack(){
  28.       Column() {
  29.         TextInput({
  30.           placeholder: "请输入用户名"
  31.         })
  32.           .fontSize(15)
  33.           .fontColor($r("app.color.text_h1"))
  34.           .type(InputType.Email)
  35.           .onChange((value) => {
  36.             this.account = value
  37.           })
  38.         TextInput({
  39.           placeholder: "请输入密码"
  40.         })
  41.           .margin({ top: 16 })
  42.           .fontSize(15)
  43.           .fontColor($r("app.color.text_h1"))
  44.           .type(InputType.Password)
  45.           .onChange((value) => {
  46.             this.password = value
  47.           })
  48.         Button("登录", {
  49.           type: ButtonType.Capsule
  50.         })
  51.           .width('100%')
  52.           .margin({ top: 50 })
  53.           .fontSize(15)
  54.           .fontColor($r("app.color.white"))
  55.           .backgroundColor($r("app.color.color_shubihong"))
  56.           .onClick((e) => {
  57.             this.login();
  58.           })
  59.       }
  60.       .width('100%')
  61.       .margin({ top: 120 })
  62.       .padding({ left: 16, right: 16 })
  63.     }
  64.     .width('100%')
  65.     .height('100%')
  66.   }
  67. }
复制代码
重点是这句:

哀求效果:

总结
以上网路哀求的封装更多的是本身的使用风俗,也清楚有许多需要改进的空间,假如有大佬能更进一步固然更好。
写在最后

有许多小伙伴不知道该从哪里开始学习鸿蒙开发技能?也不知道鸿蒙开发的知识点重点把握的又有哪些?自学时频仍踩坑,导致浪费大量时间。效果照旧一孔之见。所以有一份实用的鸿蒙(HarmonyOS NEXT)全栈开发资料用来跟着学习是非常有必要的。
这份鸿蒙(HarmonyOS NEXT)资料包含了鸿蒙开发必把握的核心知识要点,内容包含了
最新鸿蒙全栈开发学习线路


鸿蒙HarmonyOS开发讲授视频



大厂面试真题



鸿蒙OpenHarmony源码剖析


这份资料能帮住各位小伙伴理清本身的学习思路,更加速捷有效的把握鸿蒙开发的各种知识。有需要的小伙伴自行领取,,先到先得~无套路领取!!

获取这份完备版高清学习路线,请点击→鸿蒙全栈开发学习资料


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

美丽的神话

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表