#鸿蒙通关秘籍#如何在鸿蒙HarmonyOS中封装网络请求并实现登录功能

HarmonyOS
2024-12-02 13:43:24
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
WAN碧波荡漾

首先,需要在module.json5中配置基础网络权限:

"requestPermissions": [
    {
      "name": "ohos.permission.INTERNET",
    }
]

接下来,封装一个异步的请求方法:

async function requestSync<T>(path: string, method: http.RequestMethod, extraData?: Object): Promise<Response<T>> {
  return new Promise<Response<T>>((resolve, reject) => {
    let url = NetConstants.BASE_URL + path;
    let header: HeaderInterFace = {
      ApiVersion: '272',
      'Content-Type': 'application/json',
      platform: '',
      'encryption-mode': 'base64',
      auth: NetConstants.AUTH,
      channel: 'JYB',
      timeout : NetConstants.TIMEOUT
    }
    if (method === http.RequestMethod.POST) {
      header['Content-Type'] = 'application/x-www-form-urlencoded';
    }
    let httpRequest = http.createHttp();
    httpRequest.request(
      url,
      {
        method: method,
        expectDataType: http.HttpDataType.OBJECT,
        header: header,
        extraData: extraData
      },
      (err, data) => {
        let res = new Response<T>()
        if (!err && data.responseCode === 200) {
          res.data = typeof data.result === 'string' ? JSON.parse(data.result) : data.result;
        } else {
          res.errorCode = data?.responseCode ?? -1;
          res.errorMsg = err?.message ?? "";
        }
        resolve(res);
      }
    )
  })
}

然后,实现登录和其他基本功能的封装接口:

export default class Api {
  private static instance: Api;

  private constructor() {}

  static net(): Api {
    if (Api.instance === undefined) {
      Api.instance = new Api();
    }
    return Api.instance;
  }

  async login(username: string, password: string): Promise<Response<UserData>> {
    return requestSync("/user/login", http.RequestMethod.POST, `username=${username}&password=${password}`);
  }

  async logout(): Promise<Response<string>> {
    return requestSync("/user/logout/json", http.RequestMethod.GET);
  }

  async getUserInfo(): Promise<Response<UserData>> {
    return requestSync("/lg/coin/userinfo/json", http.RequestMethod.GET);
  }
}

interface HeaderInterFace {
  'ApiVersion': string,
  'Content-Type': string,
  'platform': string,
  'encryption-mode': string,
  'auth': string,
  'channel': string,
  'timeout': number
}

在组件中实现登录功能:

@Entry
@Component
export struct Login {

  @State showLoading: boolean = false;
  @State title: string = "登录";
  private account: string = "";
  private password: string = "";

  async login() {
    if (!this.account) {
      toast("请输入用户名");
      return;
    }
    if (!this.password) {
      toast("请输入密码");
      return;
    }
    this.showLoading = true;
    let res = await Api.net().login(this.account, this.password);
    this.showLoading = false;
    if (res.isSuccessWithData()) {
      toast("登录成功");
    } else {
      toast(res.errorMsg);
    }
  }

  build() {

    Stack() {
      Column() {
        TextInput({
          placeholder: "请输入用户名"
        })
          .fontSize(15)
          .fontColor($r("app.color.text_h1"))
          .type(InputType.Email)
          .onChange((value) => {
            this.account = value
          })
        TextInput({
          placeholder: "请输入密码"
        })
          .margin({ top: 16 })
          .fontSize(15)
          .fontColor($r("app.color.text_h1"))
          .type(InputType.Password)
          .onChange((value) => {
            this.password = value
          })
        Button("登录", {
          type: ButtonType.Capsule
        })
          .width('100%')
          .margin({ top: 50 })
          .fontSize(15)
          .fontColor($r("app.color.white"))
          .backgroundColor($r("app.color.color_shubihong"))
          .onClick((e) => {
            this.login();
          })
      }
      .width('100%')
      .margin({ top: 120 })
      .padding({ left: 16, right: 16 })
    }
    .width('100%')
    .height('100%')
  }
}

该方案包含了网络请求的封装和最基本的登录页面实现,方便根据项目具体需求进行进一步的扩展和深入开发。

分享
微博
QQ
微信
回复
2024-12-02 16:49:34
相关问题