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

团队介绍

作者:徐庆

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

前言:

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

效果图

响应数据效果

使用本地网络服务

接口说明:

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

客户端具体实现:

复制代码
"requestPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  }
]

如图

网络请求 工具类实现

复制代码
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提示

最后总结 :

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

相关推荐
盟接之桥1 小时前
当大模型遇见线束制造:不是通用AI,而是行业AI
大数据·网络·人工智能·安全·制造
91刘仁德2 小时前
IP协议详解:从IP协议头到网段划分、路由与NAT
linux·服务器·网络·网络协议·tcp/ip
可乐鸡翅yeah_3 小时前
业务中 M3U8 水印相关坑,硬水印和动态水印区别
前端·网络·数据库·ffmpeg·m3u8在线
梦想不只是梦与想4 小时前
HarmonyOS应用分层架构设计
harmonyos·分层架构·一次开发,多端部署
传奇开心果编程5 小时前
【Compose Multiplatform 跨端开发学与练】第7课 平台适配与互操作
android·windows·学习·ui·ios·kotlin·composer
酣大智5 小时前
H3C MSR3600 交换机配置 SSH
网络·ssh·智能路由器
沐浴露z5 小时前
Agent 响应延迟过高?从工具治理角度提供两条思路
前端·网络
MardaWang6 小时前
当滚动逃离了框架 ——HarmonyOS Web 与原生混排滚动的冲突本质与解法
harmonyos·arkts·鸿蒙·deveco studio
马六六i6 小时前
市面上正规的IP驱动产业新场景新工具有哪些
大数据·网络·python·tcp/ip