鴻蒙 Ark UI 實戰(zhàn)登錄界面請求網(wǎng)絡(luò)實現(xiàn)教程

前言:

各位同學(xué)有段時間沒有見面 因為一直很忙所以就沒有去更新博客。最近有在學(xué)習(xí)這個鴻蒙的ark ui開發(fā) 因為鴻蒙不是發(fā)布了一個鴻蒙next的測試版本 明年會啟動純血鴻蒙應(yīng)用 所以我就想提前給大家寫一些博客文章

效果圖

image.png

image.png

響應(yīng)數(shù)據(jù)效果

image.png

使用本地網(wǎng)絡(luò)服務(wù)

image.png

接口說明:

接口是我本地使用springboot 框架配合 hibernate 配合jpa寫的一個后臺服務(wù) :

客戶端具體實現(xiàn):

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

如圖

[圖片上傳失敗...(image-ee5038-1701866510795)]

網(wǎng)絡(luò)請求 工具類實現(xiàn)

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 // 請求參數(shù)
  });
  return responseResult.then((value: http.HttpResponse)=>{
      Logger.error("請求狀態(tài) --> "+value.responseCode)
     if(value.responseCode===200){
       Logger.error("請求成功");
       let getresult = value.result;
       Logger.error('請求返回數(shù)據(jù)', JSON.stringify(getresult));
       return getresult;
     }
  }).catch((err)=>{
    return "";
  });
}

打印日志工具類實現(xiàn) :



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)

登錄界面實現(xiàn) :

/**
 * 創(chuàng)建人:xuqing
 * 創(chuàng)建時間: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("登錄請求回調(diào)結(jié)果 ---> " +data.toString());
        let obj=JSON.parse(data.toString());
        Logger.error("請求結(jié)果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')
    })
  }
}

點擊登錄拿到輸入數(shù)據(jù)和后臺交互

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("登錄請求回調(diào)結(jié)果 ---> " +data.toString());
       let obj=JSON.parse(data.toString());
       Logger.error("請求結(jié)果code -- > "+obj.code);
       if(obj.code===200){
         prompt.showToast({
           message: $r('app.string.login_success')
         })
       }
     });
   }
 }

這邊我們拿到輸入框的數(shù)據(jù) 然后進行空判 非空后 我們把請求參數(shù)拼接在我們的 url 后面去調(diào)用工具類方法請求服務(wù)器去驗證登錄 。

異步調(diào)用請求方法

await   httpRequestGet(networkurl).then((data)=>{
  console.log("data --- > "+data);
  Logger.error("登錄請求回調(diào)結(jié)果 ---> " +data.toString());
  let obj=JSON.parse(data.toString());
  Logger.error("請求結(jié)果code -- > "+obj.code);
  if(obj.code===200){
    prompt.showToast({
      message: $r('app.string.login_success')
    })
  }
});

josn解析

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

請求成功后toast提示

image.png

最后總結(jié) :

這個簡單案例包含了網(wǎng)絡(luò)請求 布局還有 數(shù)據(jù)回調(diào) 字符串拼接 知識點還是很多,回調(diào)寫法和flutter 很像 這邊字符串拼接 直接+ 號拼接我寫很low希望網(wǎng)友可以優(yōu)化 還有json解析 后面我會專門講解的 現(xiàn)在篇幅有限就不展開講了 有興趣的同學(xué)可以把代碼下載出來再研究 最后呢 希望我都文章能幫助到各位同學(xué)工作和學(xué)習(xí) 如果你覺得文章還不錯麻煩給我三連 關(guān)注點贊和轉(zhuǎn)發(fā) 謝謝

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容