鸿蒙开发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()
  })
}
相关推荐
Damon小智6 小时前
HarmonyOS NEXT 技术实践-基于基础视觉服务的多目标识别
华为·harmonyos
爱笑的眼睛111 天前
uniapp 极速上手鸿蒙开发
华为·uni-app·harmonyos
K.P1 天前
鸿蒙元服务从0到上架【第三篇】(第二招有捷径)
华为·harmonyos·鸿蒙系统
K.P1 天前
鸿蒙元服务从0到上架【第二篇】
华为·harmonyos·鸿蒙系统
敲代码的小强1 天前
Flutter项目兼容鸿蒙Next系统
flutter·华为·harmonyos
程序猿会指北1 天前
纯血鸿蒙APP实战开发——Text实现部分文本高亮和超链接样式
移动开发·harmonyos·arkts·openharmony·arkui·组件化·鸿蒙开发
鸿蒙自习室1 天前
鸿蒙开发——关系型数据库的基本使用与跨设备同步
前端·数据库·华为·harmonyos·鸿蒙
SoraLuna2 天前
「Mac畅玩鸿蒙与硬件45」UI互动应用篇22 - 评分统计工具
开发语言·macos·ui·华为·harmonyos
资讯分享周2 天前
鸿蒙风起,未来已来——云学堂鸿蒙应用认证开营啦!
华为·harmonyos
Lincode122 天前
HarmonyOS--鸿蒙三方库--lottie
华为·harmonyos