鸿蒙开发HarmonyOS Next 网络框架retrofit 封装 viemodel使用

新手刚开始学习harmonyos开发,之前搞安卓开发习惯使用retrofit,结果在三方库中还真搜到了,然后就模拟学习一下。有不对的地方请指点一下。新手新手

oh-package.json5 引入库

retofit 需要使用2.0.1-rc.0 以上版本,修复了retrofit发送网络请求,响应结果未正常解析的问题。

复制代码
   "@ohos/retrofit": "2.0.1-rc.0",
   "@ohos/httpclient": "2.0.1-rc.5",

页面使用

复制代码
@Entry
@Component
struct LoginPage {
  @State viewModel: LoginViewModel = new LoginViewModel()

    .....省略
        Button("登录")
          .width("85%")
          .height(50)
          .margin({ top: 65 })
          .onClick(() => {

            if (StrUtil.isEmpty(this.viewModel.userName)) {
              ToastUtil.showToast("请输入用户名")
              return
            }

            if (StrUtil.isEmpty(this.viewModel.password)) {
              ToastUtil.showToast("请输入密码")
              return
            }
            this.viewModel.getToken()
          })

}

viewmodel使用

复制代码
@Observed
export class LoginViewModel {
  userName: string = ""
  password: string = ""
 .....省略
  getToken() {
    let params = new Map<string, undefined>()
    params["username"] = this.userName
    params["password"] = this.password

    baseApiRequest<Token>(
      appService.getToken(params),
      (result) => {
        Logger.debug("" + result.accessToken)
      },
        //可选参数,可不传
      {
        onFailed: (error) => {
        }, showLoading: true, loadingStr: "zzzzzzz"
      }
    )
  }
}

定义接口

复制代码
@BasePath("/")
export class AppService extends BaseService {

  @GET("szy/uaa/oauth/token")
  async getToken(@QueryMap params: Map<string, undefined>): Promise<Response<ApiResponse<Token>>> {
    return {} as Response<ApiResponse<Token>>
  }
}

httpclient 拦截器

复制代码
export class LoggingInterceptor implements Interceptor {
  async intercept(chain: Chain): Promise<Response> {
    try {
      let request = chain.requestI()
      let requestBody: RequestBody = request.body
      let url = request.url as HttpUrl
      const connectResponse = await chain.proceedI(chain.requestI())
      let startMessage = `-->${request.method} ${url.url} ${connectResponse.protocol ?? ''}`
      let contentType: string = requestBody.content
      let endMessage = `--> END ${request.method}`
      LoggerUtils.debug("添加日志拦截器")
      LoggerUtils.debug(`Headers:${JSON.stringify(request.headers)}`)
      LoggerUtils.debug("httpStart = " + startMessage)
      LoggerUtils.debug("contentType = " + contentType)
      LoggerUtils.debug("Response = " + connectResponse.result)
      LoggerUtils.debug("httpEnd = " + endMessage)
      return connectResponse
    } catch (error) {
      LoggerUtils.debug("添加日志拦截器 失败")
      return new Promise<Response>((resolve, reject) => {
        let request = chain.requestI()
        let response = chain.proceedI(request)
        response.then((data) => {
          resolve(data)
        }).catch((err: Error) => {
          reject(err)
        });
      })
    }
  }
}

RetrofitApi.ets简单封装

复制代码
import { HttpClient, IOException, TimeUnit } from '@ohos/httpclient'
import { Response, ServiceBuilder } from '@ohos/retrofit'
import { ToastUtil } from '@pura/harmony-utils'
import { NetworkConstants } from '../../common/NetworkConstants'
import { ApiResponse } from './ApiResponse'
import { AppService } from './AppService'
import { HeaderInterceptor } from './HeaderInterceptor'
import { LoggingInterceptor } from './LoggingInterceptor'
import { DialogUtils } from '../../common/DialogUtils'

let client: HttpClient = new  HttpClient.Builder()
  .setConnectTimeout(15, TimeUnit.SECONDS)
  .setReadTimeout(15, TimeUnit.SECONDS)
  .addInterceptor(new LoggingInterceptor())
  .addInterceptor(new HeaderInterceptor())
  .build()

export const appService = new ServiceBuilder()
  .setEndpoint(NetworkConstants.BASE_URL)
  .setClient(client)
  .build(AppService)

/**
 * 可选参数
 */
interface ApiParams {
  onFailed?: (error: ResourceStr) => void,
  showLoading?: boolean,
  loadingStr?: string
}

export function baseApiRequest<T>(
  apiCall: Promise<Response<ApiResponse<T>>>,
  onSuccess: (result: T) => void,
  param?: ApiParams,
) {
  if (param?.showLoading) {
    DialogUtils.showLoading(param.loadingStr)
  }
  apiCall.then((result: Response<ApiResponse<T>>) => {
    if (result.isSuccessful() && result.code() == 200 && result.result.success) {
      onSuccess(result.result.data)
    } else {
      ToastUtil.showToast(result.result.message)
      if (param?.onFailed) {
        param.onFailed(result.result.message)
      }
    }
    DialogUtils.dismiss()
  }).catch((error: Error) => {
    if (error as IOException) {
      if (param?.onFailed) {
        param.onFailed('error = ' + error)
      }
    } else {
      if (param?.onFailed) {
        param.onFailed(error.message)
      }
    }
    ToastUtil.showToast(error.message)
    DialogUtils.dismiss()
  })
}
相关推荐
加农炮手Jinx9 小时前
Flutter 组件 ubuntu_service 适配鸿蒙 HarmonyOS 实战:底层系统服务治理,构建鸿蒙 Linux 子系统与守护进程交互架构
flutter·harmonyos·鸿蒙·openharmony·ubuntu_service
里欧跑得慢9 小时前
Flutter 三方库 mobx_codegen — 自动化驱动的高性能响应式状态管理(适配鸿蒙 HarmonyOS Next ohos)
flutter·自动化·harmonyos
王码码20359 小时前
Flutter 三方库 login_client 的鸿蒙化适配指南 - 打造工业级安全登录、OAuth2 自动化鉴权、鸿蒙级身份守门员
flutter·harmonyos·鸿蒙·openharmony·login_client
星辰徐哥9 小时前
鸿蒙金融理财全栈项目——上线与运维、用户反馈、持续迭代
运维·金融·harmonyos
加农炮手Jinx9 小时前
Flutter 三方库 cloudflare 鸿蒙云边协同分发流适配精讲:直连全球高速存储网关阵列无缝吞吐海量动静态画像资源,构筑大吞吐业务级网络负载安全分流-适配鸿蒙 HarmonyOS ohos
网络·flutter·harmonyos
大雷神13 小时前
HarmonyOS APP<玩转React>开源教程十一:组件化开发概述
前端·react.js·harmonyos
国医中兴17 小时前
Flutter 三方库 dson 的鸿蒙化适配指南 - 极简的序列化魔法、在鸿蒙端实现反射式 JSON 映射实战
flutter·harmonyos·鸿蒙·openharmony
池央18 小时前
在鸿蒙上跑 AI Agent:JiuwenClaw-on-OpenHarmony 完整实战
人工智能·华为·harmonyos
互联网散修18 小时前
零基础鸿蒙应用开发第五节:基础数据类型与对象类型转换
华为·harmonyos·鸿蒙应用开发入门教程
弓.长.19 小时前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-fast-image — 高性能图片加载组件
react native·react.js·harmonyos