Network Implementation of Ark UI Login Interface
Network Request Utility Class
Here's the implementation of a network request utility class in TypeScript:
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, // Optional, default is 60000ms
header: {
'Content-Type': ContentType.JSON
},
connectTimeout: Constants.HTTP_READ_TIMEOUT, // Optional, default is 60000ms
extraData: params // Request parameters
});
return responseResult.then((value: http.HttpResponse) => {
Logger.error("Request status --> " + value.responseCode);
if (value.responseCode === 200) {
Logger.error("Request succeeded");
let getResult = value.result;
Logger.error('Response data:', JSON.stringify(getResult));
return getResult;
}
}).catch((err) => {
return "";
});
}
Log Printing Utility Class
Here's the implementation of a log printing utility class in Kotlin:
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 indicating the service domain, a hexadecimal integer 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);
Login Interface Implementation
Here's the implementation of the login interface:
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)
}
@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("Request URL: " + networkurl);
await httpRequestGet(networkurl).then((data) => {
console.log("Data received: " + data);
Logger.error("Login request callback result: " + data.toString());
let obj = JSON.parse(data.toString());
Logger.error("Request result 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')
})
}
}
Login Button Click Handling
When the login button is clicked, the input data is retrieved and interacted with the backend:
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("Request URL: " + networkurl);
await httpRequestGet(networkurl).then((data) => {
console.log("Data received: " + data);
Logger.error("Login request callback result: " + data.toString());
let obj = JSON.parse(data.toString());
Logger.error("Request result code: " + obj.code);
if (obj.code === 200) {
prompt.showToast({
message: $r('app.string.login_success')
});
}
});
}
}
In this implementation, we retrieve the input data from the text fields and perform a null check. If the inputs are not null, we construct the request parameters and append them to the URL. Then, we call the utility class method to send a request to the server for login verification.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.