IT评测·应用市场-qidao123.com技术社区

标题: HarmonyOS NEXT应用开发实战(二、封装比UniApp和小程序更简朴好用的网络库) [打印本页]

作者: 诗林    时间: 2024-10-30 04:42
标题: HarmonyOS NEXT应用开发实战(二、封装比UniApp和小程序更简朴好用的网络库)
网络访问接口,使用频次最高。之前习惯了uniapp下的网络接口风格,使用起来贼简朴方便。转战到鸿蒙上后,原始网络接口写着真累啊!目标让鸿蒙上网络接口使用,简朴水平比肩uniapp,比Axios更轻量级。源码量也不多,但更方便定制优化,功能也不弱。
  前言

接上篇,HarmonyOS NEXT应用开发(一、打造最好用的网络通信模块组件)-CSDN博客​​​​​​网络库已经封装好啦,成功发布到了OpenHarmony三方库中心仓。地址:OpenHarmony三方库中心仓
但是现在还没人气,可能一些同伴不会用。这里特写了篇文章和使用demo,发出来让大家看下,原来写网络接口竟可以如此简朴。
有多简朴?demo源码地址:zhihudaily: HarmonyOS NEXT 项目开发实战,仿知乎日报的实现
看以下接口示例:
起首项目中先引入我发布到鸿蒙中心堆栈的h_request网络库:
  1. "dependencies": {
  2.     "@yyz116/h_request": "1.0.1"
  3.   }
复制代码
 以下home.ts的首页相关的api接口中,两行代码就写好了两个接口,够简朴清晰吧。一个是获取影视轮播图的get接口,一个是获取影视数据的post接口请求。
  1. //main/ets/common/api/home.ts
  2. import { setRequestConfig } from '../../utils/http';
  3. import { BaseResponse,SwiperData,HotMovieReq,MovieRespData } from '../bean/ApiTypes';
  4. // 调用setRequestConfig函数进行请求配置
  5. setRequestConfig();
  6. const http = globalThis.$http;
  7. // 获取轮播图api接口
  8. export const getSwiperList = (): Promise<BaseResponse<SwiperData>> => http.get('/swiperdata');
  9. // 获取热门影视接口
  10. export const getHotMovie = (req:HotMovieReq): Promise<BaseResponse<MovieRespData>> => http.post('/hotmovie',req);
复制代码


详细示例

接口实现

预备两个后台接口:
  1. ### 1.首页,影视轮播图
  2. get http://175.178.126.10:8000/api/v1/swiperdata
  3. ### 2.首页,正在热映的电影
  4. post http://175.178.126.10:8000/api/v1/hotmovie
  5. Content-Type:application/json
  6. {
  7.     "start": 0,
  8.     "count": 1,
  9.     "city": "郑州"
  10. }
复制代码
在项目工程源码ets/main/common/bean/目次下,创建网络通信json包协议的type定义:
  1. //file:ApiTypes.ts
  2. export interface BaseResponse<T>{
  3.   status: number;
  4.   statusText:string;
  5.   data:T;
  6. }
  7. export interface ErrorResponse {
  8.   code: number;
  9.   message: string;
  10.   data: [];
  11. }
  12. // 轮播图响应数据
  13. export interface SwiperItem{
  14.   id:string;
  15.   imageUrl:string;
  16.   title:string;
  17.   url:string;
  18.   description:string;
  19. }
  20. export interface SwiperData {
  21.   code: number;
  22.   message: string;
  23.   data: Array<SwiperItem>;
  24. }
  25. // 热门影视请求数据
  26. export interface HotMovieReq {
  27.   start: number;
  28.   count: number;
  29.   city:string;
  30. }
  31. // 热门影视响应数据
  32. interface MovieItem{
  33.   id:string;
  34.   cover:string;
  35.   title:string;
  36.   gener:string;
  37.   rate:number;
  38. }
  39. export interface MovieRespData {
  40.   code: number;
  41.   message: string;
  42.   data: Array<MovieItem>;
  43.   count: number;
  44.   start: number;
  45.   total: number;
  46.   title: string;
  47. }
复制代码
创建个utils文件夹,放置封装的http.ts工具类,这个主要用来设置全局后台服务地址,参数和设置全局拦截器,并把其网络请求实例挂载在ArkTS引擎实例内部的一个全局对象globalThis中,供全局使用。
  1. import Request, { HttpRequestConfig, HttpResponse } from '@yyz116/h_request'
  2. import { Log } from './logutil';
  3. const $u = {
  4.   http: new Request(),
  5. }
  6. //挂载在ArkTS引擎实例内部的一个全局对象globalThis中,供全局使用
  7. globalThis.$http = $u.http;
  8. export const setRequestConfig = () => {
  9.   globalThis.$http.setConfig((config:HttpRequestConfig) => {
  10.     config.baseURL = "http://175.178.126.10:8000/api/v1";
  11.     return config;
  12.   });
  13.   // 请求拦截
  14.   globalThis.$http.interceptors.request.use(
  15.     (config) => {
  16.       Log.debug('请求拦截')
  17.       return config
  18.     },
  19.     (error) => {
  20.       return Promise.reject(error)
  21.     }
  22.   )
  23.   // 响应拦截
  24.   globalThis.$http.interceptors.response.use(
  25.     (response:HttpResponse) => {
  26.       Log.debug('响应拦截')
  27.       if (response.data.code == 401) {
  28.         // 提示重新登录
  29.         console.log('请登录')
  30.         setTimeout(() => {
  31.           console.log('请请登录')
  32.         }, 1000);
  33.       }
  34.       return response
  35.     },
  36.     (error) => {
  37.       return Promise.reject(error)
  38.     }
  39.   )
  40. }
复制代码
接下来就是写接口啦,以下示例一个是get接口使用,一个是post接口使用,且带post的数据。
  1. import { setRequestConfig } from '../../utils/http';
  2. import { BaseResponse,SwiperData,HotMovieReq,MovieRespData } from '../bean/ApiTypes';
  3. // 调用setRequestConfig函数进行请求配置
  4. setRequestConfig();
  5. const http = globalThis.$http;
  6. // 获取轮播图api接口
  7. export const getSwiperList = (): Promise<BaseResponse<SwiperData>> => http.get('/swiperdata');
  8. // 获取热门影视接口
  9. export const getHotMovie = (req:HotMovieReq): Promise<BaseResponse<MovieRespData>> => http.post('/hotmovie',req);
复制代码
 假如get的接口,带参数呢?带参数的话可以如许写:
  1. // 发送get请求,带参数,实际请求为:xxx.xxx/api/v1/musicsearchlrc?id=""&kind=""
  2. http.get('api/v1/musicsearchlrc', {params:{id:"543656129",kind:"wy"}}).then((res:HttpResponse<Result>) => {
  3.               hilog.debug(0x0000,"request",res.data.message)
  4.               hilog.debug(0x0000,"request","res.data.code:%{public}d",res.data.code)
  5.             }).catch((err:HttpResponse<Error>) => {
  6.               hilog.debug(0x0000,"request","err.data.code:%d",err.data.code)
  7.               hilog.debug(0x0000,"request",err.data.message)
  8.             });
  9.           })
复制代码
怎样使用

接下来就可以在页面中愉快的使用接口啦,可以看到使用变得十分简朴。示比方下:
  1. import {getSwiperList,getHotMovie} from "../common/api/home"
  2. import { hilog } from '@kit.PerformanceAnalysisKit';
  3. import { ErrorResponse } from '../common/bean/ApiTypes';
  4. @Entry
  5. @Component
  6. struct Index {
  7.   @State message: string = 'Hello World';
  8.   // 只有被@Entry装饰的组件才可以调用页面的生命周期
  9.   onPageShow() {
  10.     console.info('Index onPageShow');
  11.   }
  12.   // 只有被@Entry装饰的组件才可以调用页面的生命周期
  13.   onPageHide() {
  14.     console.info('Index onPageHide');
  15.   }
  16.   // 只有被@Entry装饰的组件才可以调用页面的生命周期
  17.   onBackPress() {
  18.     console.info('Index onBackPress');
  19.   }
  20.   // 组件生命周期
  21.   aboutToAppear() {
  22.     console.info('MyComponent aboutToAppear');
  23.   }
  24.   // 组件生命周期
  25.   aboutToDisappear() {
  26.     console.info('MyComponent aboutToDisappear');
  27.   }
  28.   build() {
  29.     Row() {
  30.       Column() {
  31.         Text(this.message)
  32.           .id('HelloWorld')
  33.           .fontSize(50)
  34.           .fontWeight(FontWeight.Bold)
  35.         Button('test')
  36.           .onClick(() => {
  37.             console.info('button click');
  38.             getSwiperList().then((res) => {
  39.               hilog.debug(0x0000,"request",res.data.message)
  40.               hilog.debug(0x0000,"request","res.data.code:%{public}d",res.data.code)
  41.               hilog.debug(0x0000,"request","res.data.data[0]:%{public}s",res.data.data[0].id)
  42.               hilog.debug(0x0000,"request","res.data.data[0]:%{public}s",res.data.data[0].imageUrl)
  43.               hilog.debug(0x0000,"request","res.data.data[0]:%{public}s",res.data.data[0].title)
  44.             }).catch((err:ErrorResponse) => {
  45.               hilog.debug(0x0000,"request","err.data.code:%d",err.code)
  46.               hilog.debug(0x0000,"request",err.message)
  47.             });
  48.             getHotMovie({start:0,count:1,city:"郑州"}).then((res) => {
  49.               hilog.debug(0x0000,"request",res.data.message)
  50.               hilog.debug(0x0000,"request","res.data.code:%{public}d",res.data.code)
  51.               hilog.debug(0x0000,"request","res.data.data[0]:%{public}s",res.data.data[0].id)
  52.               hilog.debug(0x0000,"request","res.data.data[0]:%{public}s",res.data.data[0].gener)
  53.               hilog.debug(0x0000,"request","res.data.data[0]:%{public}s",res.data.data[0].title)
  54.             }).catch((err:ErrorResponse) => {
  55.               hilog.debug(0x0000,"request","err.data.code:%d",err.code)
  56.               hilog.debug(0x0000,"request",err.message)
  57.             });
  58.           })
  59.       }
  60.       .height('100%')
  61.       .width('100%')
  62.     }
  63.   }
  64. }
复制代码
总结

以上就是笔者封装的鸿蒙开源库h_request的使用先容。可以看出使用此网络封装库后,在鸿蒙的网络服务开发上,也可以体验到如uniapp小程序开发般的简朴易用。分享给有需要的小同伴,接待留言评论并提名贵意见,最终打造出一个在鸿蒙平台上最简朴好用的网络库。
写在末了

末了,推荐下笔者的业余开源app影视项目“爱影家”,推荐分享给与我一样喜欢观影的朋侪。
开源地址:爱影家app开源项目先容及源码
  1. https://gitee.com/yyz116/imovie
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4