鸿蒙 Ark ui 实战登录界面请求网络实现教程

团队介绍

作者:徐庆

团队:坚果派 公众号:“大前端之旅” 润开鸿生态技术专家,华为HDE,CSDN博客专家,CSDN超级个体,CSDN特邀嘉宾,InfoQ签约作者,OpenHarmony布道师,电子发烧友专家博客,51CTO博客专家,擅长HarmonyOS/OpenHarmony应用开发、熟悉服务卡片开发。欢迎合作。

前言:

各位同学有段时间没有见面 因为一直很忙所以就没有去更新博客。最近有在学习这个鸿蒙的ark ui开发 因为鸿蒙不是发布了一个鸿蒙next的测试版本 明年会启动纯血鸿蒙应用 所以我就想提前给大家写一些博客文章

效果图

image.png

image.png

响应数据效果

image.png

使用本地网络服务

image.png

接口说明:

接口是我本地使用springboot 框架配合 hibernate 配合jpa写的一个后台服务 :

客户端具体实现:

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

如图

image.png

网络请求 工具类实现

import http from '@ohos.net.http';
import Constants, { ContentType } from '../constant/Constants';
import Logger from './Logger';
import { NewsData } from '../viewmodel/NewsData';


export function httpRequestGet(url: string) {
  return httpRequest(url, http.RequestMethod.GET);
}

export function httpRequestPost(url: string, params?: NewsData) {
  return httpRequest(url, http.RequestMethod.POST, params);
}

function httpRequest(url: string, method: http.RequestMethod,params?: NewsData){
  let httpRequest = http.createHttp();
  let responseResult = httpRequest.request(url, {
    method: method,
    readTimeout: Constants.HTTP_READ_TIMEOUT,//读取超时时间 可选,默认为60000ms
    header: {
      'Content-Type': ContentType.JSON
    },
    connectTimeout: Constants.HTTP_READ_TIMEOUT,//连接超时时间  可选,默认为60000ms
    extraData: params // 请求参数
  });
  return responseResult.then((value: http.HttpResponse)=>{
      Logger.error("请求状态 --> "+value.responseCode)
     if(value.responseCode===200){
       Logger.error("请求成功");
       let getresult = value.result;
       Logger.error('请求返回数据', JSON.stringify(getresult));
       return getresult;
     }
  }).catch((err)=>{
    return "";
  });
}

打印日志工具类实现 :



import hilog from '@ohos.hilog';

class Logger {
  private domain: number;
  private prefix: string;
  private format: string = '%{public}s, %{public}s';

  /**
   * constructor.
   *
   * @param Prefix Identifies the log tag.
   * @param domain Domain Indicates the service domain, which is a hexadecimal integer ranging from 0x0 to 0xFFFFF.
   */
  constructor(prefix: string = 'MyApp', domain: number = 0xFF00) {
    this.prefix = prefix;
    this.domain = domain;
  }

  debug(...args: string[]): void {
    hilog.debug(this.domain, this.prefix, this.format, args);
  }

  info(...args: string[]): void {
    hilog.info(this.domain, this.prefix, this.format, args);
  }

  warn(...args: string[]): void {
    hilog.warn(this.domain, this.prefix, this.format, args);
  }

  error(...args: string[]): void {
    hilog.error(this.domain, this.prefix, this.format, args);
  }
}

export default new Logger('HTTPS', 0xFF00)

登录界面实现 :

/**
 * 创建人:xuqing
 * 创建时间:2023年8月2日08:38:50
 * 类说明:
 *
 *
 */
import prompt from '@ohos.promptAction';
import router from '@ohos.router';
import CommonConstants from '../common/constant/CommonConstants';
import StyleConstant from '../common/constant/StyleConstant';
import { httpRequestGet }  from '../common/utils/OKhttpUtil';
import CommonConstant from '../common/constant/CommonConstants';
import  Logger from '../common/utils/Logger';



@Extend(TextInput) function inputStyle () {
  .placeholderColor($r('app.color.placeholder_color'))
  .height($r('app.float.login_input_height'))
  .fontSize($r('app.float.big_text_size'))
  .backgroundColor($r('app.color.background'))
  .width(CommonConstants.FULL_PARENT)
  .padding({ left: CommonConstants.INPUT_PADDING_LEFT })
  .margin({ top: $r('app.float.input_margin_top') })
}

@Extend(Line) function lineStyle () {
  .width(CommonConstants.FULL_PARENT)
  .height($r('app.float.line_height'))
  .backgroundColor($r('app.color.line_color'))
}

@Extend(Text) function blueTextStyle () {
  .fontColor($r('app.color.login_blue_text_color'))
  .fontSize($r('app.float.small_text_size'))
  .fontWeight(FontWeight.Medium)
}


@Extend(Text) function blackTextStyle () {
  .fontColor($r('app.color.black_text_color'))
  .fontSize($r('app.float.big_text_size'))
  .fontWeight(FontWeight.Medium)
}


/**
 * Login page
 */
@Entry
@Component
struct LoginPage {
  @State account: string = '';
  @State password: string = '';
  @State isShowProgress: boolean = false;
  private timeOutId = null;
  @Builder imageButton(src: Resource) {
    Button({ type: ButtonType.Circle, stateEffect: true }) {
      Image(src)
    }
    .height($r('app.float.other_login_image_size'))
    .width($r('app.float.other_login_image_size'))
    .backgroundColor($r('app.color.background'))
  }



 async  login() {
    if (this.account === '' || this.password === '') {
      prompt.showToast({
        message: $r('app.string.input_empty_tips')
      })
    } else {
      let username:string='username=';
      let password:string='&password=';
      let networkurl=CommonConstant.LOGIN+username+this.account+password+this.password;
      Logger.error("请求url "+networkurl);
      await   httpRequestGet(networkurl).then((data)=>{
        console.log("data --- > "+data);
        Logger.error("登录请求回调结果 ---> " +data.toString());
        let obj=JSON.parse(data.toString());
        Logger.error("请求结果code -- > "+obj.code);
        if(obj.code===200){
          prompt.showToast({
            message: $r('app.string.login_success')
          })
        }
      });
    }
  }

  aboutToDisappear() {
    clearTimeout(this.timeOutId);
    this.timeOutId = null;
  }

  build() {
    Column() {
      Image($r('app.media.logo'))
        .width($r('app.float.logo_image_size'))
        .height($r('app.float.logo_image_size'))
        .margin({ top: $r('app.float.logo_margin_top'), bottom: $r('app.float.logo_margin_bottom') })
      Text($r('app.string.login_page'))
        .fontSize($r('app.float.page_title_text_size'))
        .fontWeight(FontWeight.Medium)
        .fontColor($r('app.color.title_text_color'))
      Text($r('app.string.login_more'))
        .fontSize($r('app.float.normal_text_size'))
        .fontColor($r('app.color.login_more_text_color'))
        .margin({ bottom: $r('app.float.login_more_margin_bottom'), top: $r('app.float.login_more_margin_top') })

      Row() {
        //账号
        Text($r('app.string.account')).blackTextStyle()
        TextInput({ placeholder: $r('app.string.account') })
          .maxLength(CommonConstants.INPUT_ACCOUNT_LENGTH)
          .type(InputType.Number)
          .inputStyle()
          .onChange((value: string) => {
            this.account = value;
          }).margin({left:20})
      }
      .justifyContent(FlexAlign.SpaceBetween)
      .width(CommonConstants.FULL_PARENT)
      .margin({ top: $r('app.float.forgot_margin_top') })

      Line().lineStyle().margin({left:80})

      Row() {
        //密码
        Text($r('app.string.password')).blackTextStyle()
        TextInput({ placeholder: $r('app.string.password') })
          .maxLength(CommonConstants.INPUT_PASSWORD_LENGTH)
          .type(InputType.Password)
          .inputStyle()
          .onChange((value: string) => {
            this.password = value;
          }).margin({left:20})
      }
      .justifyContent(FlexAlign.SpaceBetween)
      .width(CommonConstants.FULL_PARENT)
      .margin({ top: $r('app.float.forgot_margin_top') })

      Line().lineStyle().margin({left:80})

      Row() {
        //短信验证码登录
        Text($r('app.string.message_login')).blueTextStyle().onClick(()=>{
          prompt.showToast({
            message: $r('app.string.stay_tuned_during_feature_development')
          })
        })
        //忘记密码
        Text($r('app.string.forgot_password')).blueTextStyle().onClick(()=>{
          prompt.showToast({
            message: $r('app.string.stay_tuned_during_feature_development')
          })
        })
      }
      .justifyContent(FlexAlign.SpaceBetween)
      .width(CommonConstants.FULL_PARENT)
      .margin({ top: $r('app.float.forgot_margin_top') })

      Button($r('app.string.login'), { type: ButtonType.Capsule })
        .width(CommonConstants.BUTTON_WIDTH)
        .height($r('app.float.login_button_height'))
        .fontSize($r('app.float.normal_text_size'))
        .fontWeight(FontWeight.Medium)
        .backgroundColor($r('app.color.login_button_color'))
        .margin({ top: $r('app.float.login_button_margin_top'), bottom: $r('app.float.login_button_margin_bottom') })
        .onClick(() => {
          this.login();
        })
      Text($r('app.string.register_account')).onClick(()=>{
        prompt.showToast({
          message: $r('app.string.stay_tuned_during_feature_development')
        })
      }).fontColor($r('app.color.login_blue_text_color'))
        .fontSize($r('app.float.normal_text_size'))
        .fontWeight(FontWeight.Medium)

      if (this.isShowProgress) {
        LoadingProgress()
          .color($r('app.color.loading_color'))
          .width($r('app.float.login_progress_size'))
          .height($r('app.float.login_progress_size'))
          .margin({ top: $r('app.float.login_progress_margin_top') })
      }
      Blank()
    }
    .backgroundColor($r('app.color.background'))
    .height(CommonConstants.FULL_PARENT)
    .width(CommonConstants.FULL_PARENT)
    .padding({
      left: $r('app.float.page_padding_hor'),
      right: $r('app.float.page_padding_hor'),
      bottom: $r('app.float.login_page_padding_bottom')
    })
  }
}

点击登录拿到输入数据和后台交互

async  login() {
   if (this.account === '' || this.password === '') {
     prompt.showToast({
       message: $r('app.string.input_empty_tips')
     })
   } else {
     let username:string='username=';
     let password:string='&password=';
     let networkurl=CommonConstant.LOGIN+username+this.account+password+this.password;
     Logger.error("请求url "+networkurl);
     await   httpRequestGet(networkurl).then((data)=>{
       console.log("data --- > "+data);
       Logger.error("登录请求回调结果 ---> " +data.toString());
       let obj=JSON.parse(data.toString());
       Logger.error("请求结果code -- > "+obj.code);
       if(obj.code===200){
         prompt.showToast({
           message: $r('app.string.login_success')
         })
       }
     });
   }
 }

这边我们拿到输入框的数据 然后进行空判 非空后 我们把请求参数拼接在我们的 url 后面去调用工具类方法请求服务器去验证登录 。

异步调用请求方法

await   httpRequestGet(networkurl).then((data)=>{
  console.log("data --- > "+data);
  Logger.error("登录请求回调结果 ---> " +data.toString());
  let obj=JSON.parse(data.toString());
  Logger.error("请求结果code -- > "+obj.code);
  if(obj.code===200){
    prompt.showToast({
      message: $r('app.string.login_success')
    })
  }
});

josn解析

let obj=JSON.parse(data.toString());
Logger.error("请求结果code -- > "+obj.code);
if(obj.code===200){
 prompt.showToast({
   message: $r('app.string.login_success')
 })
}

请求成功后toast提示

image.png

最后总结 :

这个简单案例包含了网络请求 布局还有 数据回调 字符串拼接 知识点还是很多,回调写法和flutter 很像 这边字符串拼接 直接+ 号拼接我写很low希望网友可以优化 还有json解析 后面我会专门讲解的 现在篇幅有限就不展开讲了 有兴趣的同学可以把代码下载出来再研究 最后呢 希望我都文章能帮助到各位同学工作和学习 如果你觉得文章还不错麻烦给我三连 关注点赞和转发 谢谢

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xq9527--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值