当前位置:   article > 正文

零基础开始学习鸿蒙开发-登录界面获取参数的值,并且发送参数请求后台登录,经过后台校验即可登录成功_鸿蒙开发权限配置

鸿蒙开发权限配置

上代码之前,我们需要注意两点:

一、首先要添加鸿蒙的网络权限,如果不添加权限,后面代码完成之后,可能请求失败。

二、鸿蒙模拟器不支持本地localhost 、127.0.01本地地址的请求,所有的请求只能通过公网发起请求。

三、添加权限的方法:

    1).找到项目的module.json5文件夹,在此文件夹添加如下代码:

  1. "requestPermissions": [
  2. {
  3. "name": "ohos.permission.INTERNET"
  4. }
  5. ]

   2).以下是我的权限配置所有代码:

  1. {
  2. "module": {
  3. "name": "entry",
  4. "type": "entry",
  5. "description": "$string:module_desc",
  6. "mainElement": "EntryAbility",
  7. "deviceTypes": [
  8. "phone",
  9. "tablet"
  10. ],
  11. "deliveryWithInstall": true,
  12. "installationFree": false,
  13. "pages": "$profile:main_pages",
  14. "abilities": [
  15. {
  16. "name": "EntryAbility",
  17. "srcEntry": "./ets/entryability/EntryAbility.ts",
  18. "description": "$string:EntryAbility_desc",
  19. "icon": "$media:icon",
  20. "label": "$string:EntryAbility_label",
  21. "startWindowIcon": "$media:icon",
  22. "startWindowBackground": "$color:start_window_background",
  23. "exported": true,
  24. "skills": [
  25. {
  26. "entities": [
  27. "entity.system.home"
  28. ],
  29. "actions": [
  30. "action.system.home"
  31. ]
  32. }
  33. ]
  34. }
  35. ],
  36. "requestPermissions": [
  37. {
  38. "name": "ohos.permission.INTERNET"
  39. }
  40. ]
  41. }
  42. }

四、创建httpPost请求组件类

    4.1在头部导入http请求模块

import http from '@ohos.net.http';

      4.2  创建http连接

 let request = http.createHttp();

      4.3 封装请求体和请求参数

  1. let options = {
  2. method: http.RequestMethod.POST,
  3. header: { 'Content-Type': 'application/json','charset':'utf-8'},
  4. extraData:{
  5. "username":username,
  6. "password":password
  7. },
  8. readTimeout: 72000,
  9. connectTimeout: 72000
  10. } as http.HttpRequestOptions;

        4.4 异步发起http请求

let result = await request.request(url, options);

         4.5 下面是完整的请求组件代码,即HttpUtil.ets

     

  1. /*
  2. * Copyright (c) 2023 Huawei Device Co., Ltd.
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import http from '@ohos.net.http';
  16. // @ts-ignore
  17. export default async function postReqeust(url: string,username:string,password:string) {
  18. if (!url) {
  19. return undefined;
  20. }
  21. let request = http.createHttp();
  22. let options = {
  23. method: http.RequestMethod.POST,
  24. header: { 'Content-Type': 'application/json','charset':'utf-8'},
  25. extraData:{
  26. "username":username,
  27. "password":password
  28. },
  29. readTimeout: 72000,
  30. connectTimeout: 72000
  31. } as http.HttpRequestOptions;
  32. let result = await request.request(url, options);
  33. return result;
  34. }

      五、登录页面点击登录后,把获取到的参数,请求到后台,后台进行校验。

   5.1下面是对之前封装的请求方法进行调用

  1. //发送异步请求
  2. let res = await postReqeust("http://ntek44b.nat.ipyingshe.com/login",this.username,this.password);
  3. if(res.responseCode==200){
  4. this.colorParm = Color.Green;
  5. this.message ="登录成功";
  6. }else {
  7. this.colorParm = Color.Red;
  8. this.message ="登录失败!";
  9. }

5.2 下面是补充完整之后的登录代码。

  1. /*
  2. @Entry
  3. @Component
  4. struct Index {
  5. @State message: string = 'Hello Worlczxcxzd'
  6. build() {
  7. Row() {
  8. Column() {
  9. Text(this.message)
  10. .fontSize(50)
  11. .fontWeight(FontWeight.Bold)
  12. }
  13. .width('100%')
  14. }
  15. .height('100%')
  16. }
  17. }*/
  18. import http from '@ohos.net.http';
  19. import httpPost from '../utils/HttpUtil';
  20. import postReqeust from '../utils/HttpUtil';
  21. @Entry
  22. @Component
  23. struct registePage{
  24. //定义用户名
  25. @State username:string ="";
  26. //定义密码
  27. @State password:string ="";
  28. //定义重复用户名密码
  29. @State repeatPwd:string ="";
  30. //判断是否为空的标志
  31. @State isBlank:boolean=false;
  32. //提示语
  33. @State message:string ="";
  34. //全局URL
  35. @State URL:string ="http://127.0.0.1:8083";
  36. //定义颜色的值
  37. // @ts-ignore
  38. @State colorParm:Color = Color.Gray;
  39. //判断输入的参数是否为空方法
  40. isEmty(username:string,password:string,repeatPwd:string){
  41. //判断用户名是否为空
  42. if(username==null ||username==""){
  43. console.debug("用户名为空----");
  44. return true;
  45. }
  46. if(password==null ||password==""){
  47. console.debug("密码为空----");
  48. return true;
  49. }
  50. if(repeatPwd==null ||repeatPwd==""){
  51. console.debug("重复输入密码为空----");
  52. return true;
  53. }
  54. }
  55. //创建请求的方法
  56. postReq(){
  57. //创建http请求
  58. var httpReq = http.createHttp();
  59. console.info("发起请求----")
  60. httpReq.request("http://ntek44b.nat.ipyingshe.com/login",{
  61. //定义请求方法
  62. method:http.RequestMethod.POST,
  63. //添加请求头
  64. header:{
  65. 'Content-Type':'application/json',
  66. 'charset':'utf-8'
  67. },
  68. //请求数据,用户名,密码
  69. extraData:{
  70. "username":this.username,
  71. "password":this.password,
  72. },
  73. connectTimeout:60000,
  74. readTimeout:72000,
  75. },(msg,data)=>{
  76. console.debug("data=={}",JSON.stringify(data))
  77. console.debug("请求完成---")
  78. //请求成功
  79. if (msg.code==200){
  80. this.colorParm = Color.Green;
  81. this.message ="登录成功!";
  82. }else {
  83. // @ts-ignore
  84. this.colorParm = Color.Red;
  85. this.message ="登录失败,请检查用户名或密码";
  86. }
  87. }
  88. );
  89. }
  90. build() {
  91. //垂直的容器
  92. Column({ space: 5 }) {
  93. Image($r("app.media.app_icon"))
  94. .width("100")
  95. .height("100")
  96. .margin(50)
  97. Column({ space: 5 }) {
  98. //输入框
  99. TextInput({ placeholder: "请输入用户名" }).type(InputType.Normal)
  100. .width("300").onChange((username: string) => {
  101. //通过onChange事件获取用户名
  102. this.username = username;
  103. console.debug("username==={}", this.username);
  104. });
  105. //密码输入框
  106. TextInput({ placeholder: "请输入密码" }).type(InputType.Password)
  107. .width("300").onChange((password: string) => {
  108. //通过onChange事件获取密码
  109. this.password = password;
  110. console.debug("password==={}", this.password);
  111. });
  112. //重新确认密码
  113. TextInput({ placeholder: "请再次输入密码" }).type(InputType.Password)
  114. .width("300").onChange((repeatPwd: string) => {
  115. //通过onChange事件获取重复输入的密码
  116. this.repeatPwd = repeatPwd;
  117. console.debug("repeatPwd==={}", this.repeatPwd);
  118. });
  119. Row({ space: 5 }) {
  120. Text("提示语:").fontColor(Color.Gray);
  121. // @ts-ignore
  122. Text(this.message).fontColor(this.colorParm);
  123. }
  124. //登录
  125. Button("登录按钮").width("50%").onClick( async () => {
  126. console.debug("登录")
  127. //判断是否为空
  128. this.isBlank = this.isEmty(this.username, this.password, this.repeatPwd);
  129. if (this.isBlank) {
  130. this.colorParm =Color.Red;
  131. this.message = "请检查参数是否为空";
  132. return;
  133. } else {
  134. //判断两次输入的密码是否正确
  135. if (this.password != this.repeatPwd) {
  136. this.colorParm =Color.Red;
  137. this.message = "两次输入的密码不一致";
  138. }
  139. }
  140. //网络请求数据库验证登录
  141. //this.postReq();
  142. //发送异步请求
  143. let res = await postReqeust("http://ntek44b.nat.ipyingshe.com/login",this.username,this.password);
  144. if(res.responseCode==200){
  145. this.colorParm = Color.Green;
  146. this.message ="登录成功";
  147. }else {
  148. this.colorParm = Color.Red;
  149. this.message ="登录失败!";
  150. }
  151. console.log("res===",JSON.stringify(res));
  152. }).backgroundColor(Color.Green);
  153. }.height("100%")
  154. .width("100%")
  155. .alignItems(HorizontalAlign.Center)
  156. .justifyContent(FlexAlign.Center)
  157. }
  158. }
  159. }

六、后端主要是用SpringBoot简单搭建的后台。

        6.1配置文件:主要包含了数据库的连接,以及端口号的设置。

  1. server:
  2. port: 8083
  3. spring:
  4. datasource:
  5. username: root
  6. password: Root@123
  7. url: jdbc:mysql://127.0.0.1:3306/harmony?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf-8
  8. driver-class-name: com.mysql.cj.jdbc.Driver
  9. mybatis:
  10. mapper-locations: classpath*:/mappers/*.xml

        6.2 下面是maven的相关依赖:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.2.6.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>harmonyreq</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>harmonyreq</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>mysql</groupId>
  26. <artifactId>mysql-connector-java</artifactId>
  27. <version>8.0.19</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.mybatis.spring.boot</groupId>
  31. <artifactId>mybatis-spring-boot-starter</artifactId>
  32. <version>2.1.3</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.projectlombok</groupId>
  36. <artifactId>lombok</artifactId>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-test</artifactId>
  41. <scope>test</scope>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-starter-web</artifactId>
  46. </dependency>
  47. </dependencies>
  48. <build>
  49. <plugins>
  50. <plugin>
  51. <groupId>org.springframework.boot</groupId>
  52. <artifactId>spring-boot-maven-plugin</artifactId>
  53. </plugin>
  54. </plugins>
  55. </build>
  56. </project>

6.3 下面的代码就不一一介绍了,有Java基础的应该都能看得懂。

  1. package com.example.harmonyreq.common;
  2. import lombok.Data;
  3. @Data
  4. public class Result {
  5. private String msg;
  6. private Object data;
  7. private Integer code;
  8. public Result(String msg,Object data,Integer code){
  9. this.msg = msg;
  10. this.data = data;
  11. this.code =code;
  12. }
  13. public Result(String msg,Object data){
  14. this.msg = msg;
  15. this.data = data;
  16. this.code =code;
  17. }
  18. public Result(){
  19. }
  20. public void success(Object data,String msg){
  21. this.data = data;
  22. this.msg = msg;
  23. this.code=200;
  24. }
  25. public void success(){
  26. this.code = 200;
  27. this.msg = "成功!";
  28. }
  29. public void fail(){
  30. this.msg ="请求失败!";
  31. this.code = 500;
  32. }
  33. }
  1. package com.example.harmonyreq.mapper;
  2. import com.example.harmonyreq.model.User;
  3. import java.util.Map;
  4. public interface UserMapper {
  5. User queryByUnamePwd(Map<String,Object> map);
  6. }
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.example.harmonyreq.mapper.UserMapper">
  6. <select id="queryByUnamePwd" parameterType="java.util.Map" resultType="com.example.harmonyreq.model.User">
  7. select <include refid="Base_Column_List"/>
  8. from tb_user
  9. <where>
  10. username = #{username}
  11. and
  12. password = #{password}
  13. </where>
  14. </select>
  15. <sql id="Base_Column_List">
  16. id,username,password
  17. </sql>
  18. </mapper>
  1. package com.example.harmonyreq.service;
  2. import com.example.harmonyreq.common.Result;
  3. import java.util.Map;
  4. public interface IUserService {
  5. Result login(Map<String,Object> params);
  6. }
  1. package com.example.harmonyreq.service.impl;
  2. import com.example.harmonyreq.common.Result;
  3. import com.example.harmonyreq.mapper.UserMapper;
  4. import com.example.harmonyreq.model.User;
  5. import com.example.harmonyreq.service.IUserService;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. @Service
  13. public class UserServiceImpl implements IUserService {
  14. private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
  15. @Autowired
  16. private UserMapper userMapper;
  17. @Override
  18. public Result login(Map<String,Object>params) {
  19. Result res = new Result();
  20. try {
  21. User user = userMapper.queryByUnamePwd(params);
  22. if (null!=user){
  23. res.success(user,"成功!");
  24. logger.info("登录成功!");
  25. }else {
  26. res.fail();
  27. }
  28. }catch (Exception e){
  29. logger.error("登录失败!{}",e.getMessage());
  30. res.fail();
  31. return res;
  32. }
  33. return res;
  34. }
  35. }
  1. package com.example.harmonyreq.controller;
  2. import com.example.harmonyreq.common.Result;
  3. import com.example.harmonyreq.service.IUserService;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.PostMapping;
  8. import org.springframework.web.bind.annotation.RequestBody;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import java.util.Map;
  12. @RestController
  13. @RequestMapping("/")
  14. public class LoginController {
  15. private Logger logger = LoggerFactory.getLogger(LoginController.class);
  16. @Autowired
  17. private IUserService userService;
  18. @PostMapping("/login")
  19. public Result login(@RequestBody Map<String,Object>params){
  20. logger.info("请求过来的参数---{}",params);
  21. return userService.login(params);
  22. }
  23. }

七、代码运行成功的界面如下图所示:

        7.1 后端请求成功的界面

        7.2 鸿蒙模拟器请求成功的界面

八、另外,简单说一下,我没有自己的服务器,我是通过内网穿透的方式请求到本地的,常用的内网穿透工具,大家可以去网上找找。此博文,我会另外绑定后端代码文件。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/247876
推荐阅读
相关标签
  

闽ICP备14008679号