上代码之前,我们需要注意两点:
一、首先要添加鸿蒙的网络权限,如果不添加权限,后面代码完成之后,可能请求失败。
二、鸿蒙模拟器不支持本地localhost 、127.0.01本地地址的请求,所有的请求只能通过公网发起请求。
三、添加权限的方法:
1).找到项目的module.json5文件夹,在此文件夹添加如下代码:
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
2).以下是我的权限配置所有代码:
{
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
"phone",
"tablet"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ts",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
]
}
],
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
四、创建httpPost请求组件类
4.1在头部导入http请求模块
import http from '@ohos.net.http';
4.2 创建http连接
let request = http.createHttp();
4.3 封装请求体和请求参数
let options = {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json','charset':'utf-8'},
extraData:{
"username":username,
"password":password
},
readTimeout: 72000,
connectTimeout: 72000
} as http.HttpRequestOptions;
4.4 异步发起http请求
let result = await request.request(url, options);
4.5 下面是完整的请求组件代码,即HttpUtil.ets
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import http from '@ohos.net.http';
// @ts-ignore
export default async function postReqeust(url: string,username:string,password:string) {
if (!url) {
return undefined;
}
let request = http.createHttp();
let options = {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json','charset':'utf-8'},
extraData:{
"username":username,
"password":password
},
readTimeout: 72000,
connectTimeout: 72000
} as http.HttpRequestOptions;
let result = await request.request(url, options);
return result;
}
五、登录页面点击登录后,把获取到的参数,请求到后台,后台进行校验。
5.1下面是对之前封装的请求方法进行调用
//发送异步请求
let res = await postReqeust("http://ntek44b.nat.ipyingshe.com/login",this.username,this.password);
if(res.responseCode==200){
this.colorParm = Color.Green;
this.message ="登录成功";
}else {
this.colorParm = Color.Red;
this.message ="登录失败!";
}
5.2 下面是补充完整之后的登录代码。
/*
@Entry
@Component
struct Index {
@State message: string = 'Hello Worlczxcxzd'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}*/
import http from '@ohos.net.http';
import httpPost from '../utils/HttpUtil';
import postReqeust from '../utils/HttpUtil';
@Entry
@Component
struct registePage{
//定义用户名
@State username:string ="";
//定义密码
@State password:string ="";
//定义重复用户名密码
@State repeatPwd:string ="";
//判断是否为空的标志
@State isBlank:boolean=false;
//提示语
@State message:string ="";
//全局URL
@State URL:string ="http://127.0.0.1:8083";
//定义颜色的值
// @ts-ignore
@State colorParm:Color = Color.Gray;
//判断输入的参数是否为空方法
isEmty(username:string,password:string,repeatPwd:string){
//判断用户名是否为空
if(username==null ||username==""){
console.debug("用户名为空----");
return true;
}
if(password==null ||password==""){
console.debug("密码为空----");
return true;
}
if(repeatPwd==null ||repeatPwd==""){
console.debug("重复输入密码为空----");
return true;
}
}
//创建请求的方法
postReq(){
//创建http请求
var httpReq = http.createHttp();
console.info("发起请求----")
httpReq.request("http://ntek44b.nat.ipyingshe.com/login",{
//定义请求方法
method:http.RequestMethod.POST,
//添加请求头
header:{
'Content-Type':'application/json',
'charset':'utf-8'
},
//请求数据,用户名,密码
extraData:{
"username":this.username,
"password":this.password,
},
connectTimeout:60000,
readTimeout:72000,
},(msg,data)=>{
console.debug("data=={}",JSON.stringify(data))
console.debug("请求完成---")
//请求成功
if (msg.code==200){
this.colorParm = Color.Green;
this.message ="登录成功!";
}else {
// @ts-ignore
this.colorParm = Color.Red;
this.message ="登录失败,请检查用户名或密码";
}
}
);
}
build() {
//垂直的容器
Column({ space: 5 }) {
Image($r("app.media.app_icon"))
.width("100")
.height("100")
.margin(50)
Column({ space: 5 }) {
//输入框
TextInput({ placeholder: "请输入用户名" }).type(InputType.Normal)
.width("300").onChange((username: string) => {
//通过onChange事件获取用户名
this.username = username;
console.debug("username==={}", this.username);
});
//密码输入框
TextInput({ placeholder: "请输入密码" }).type(InputType.Password)
.width("300").onChange((password: string) => {
//通过onChange事件获取密码
this.password = password;
console.debug("password==={}", this.password);
});
//重新确认密码
TextInput({ placeholder: "请再次输入密码" }).type(InputType.Password)
.width("300").onChange((repeatPwd: string) => {
//通过onChange事件获取重复输入的密码
this.repeatPwd = repeatPwd;
console.debug("repeatPwd==={}", this.repeatPwd);
});
Row({ space: 5 }) {
Text("提示语:").fontColor(Color.Gray);
// @ts-ignore
Text(this.message).fontColor(this.colorParm);
}
//登录
Button("登录按钮").width("50%").onClick( async () => {
console.debug("登录")
//判断是否为空
this.isBlank = this.isEmty(this.username, this.password, this.repeatPwd);
if (this.isBlank) {
this.colorParm =Color.Red;
this.message = "请检查参数是否为空";
return;
} else {
//判断两次输入的密码是否正确
if (this.password != this.repeatPwd) {
this.colorParm =Color.Red;
this.message = "两次输入的密码不一致";
}
}
//网络请求数据库验证登录
//this.postReq();
//发送异步请求
let res = await postReqeust("http://ntek44b.nat.ipyingshe.com/login",this.username,this.password);
if(res.responseCode==200){
this.colorParm = Color.Green;
this.message ="登录成功";
}else {
this.colorParm = Color.Red;
this.message ="登录失败!";
}
console.log("res===",JSON.stringify(res));
}).backgroundColor(Color.Green);
}.height("100%")
.width("100%")
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
}
六、后端主要是用SpringBoot简单搭建的后台。
6.1配置文件:主要包含了数据库的连接,以及端口号的设置。
server:
port: 8083
spring:
datasource:
username: root
password: Root@123
url: jdbc:mysql://127.0.0.1:3306/harmony?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath*:/mappers/*.xml
6.2 下面是maven的相关依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>harmonyreq</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>harmonyreq</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
6.3 下面的代码就不一一介绍了,有Java基础的应该都能看得懂。
package com.example.harmonyreq.common;
import lombok.Data;
@Data
public class Result {
private String msg;
private Object data;
private Integer code;
public Result(String msg,Object data,Integer code){
this.msg = msg;
this.data = data;
this.code =code;
}
public Result(String msg,Object data){
this.msg = msg;
this.data = data;
this.code =code;
}
public Result(){
}
public void success(Object data,String msg){
this.data = data;
this.msg = msg;
this.code=200;
}
public void success(){
this.code = 200;
this.msg = "成功!";
}
public void fail(){
this.msg ="请求失败!";
this.code = 500;
}
}
package com.example.harmonyreq.mapper;
import com.example.harmonyreq.model.User;
import java.util.Map;
public interface UserMapper {
User queryByUnamePwd(Map<String,Object> map);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.harmonyreq.mapper.UserMapper">
<select id="queryByUnamePwd" parameterType="java.util.Map" resultType="com.example.harmonyreq.model.User">
select <include refid="Base_Column_List"/>
from tb_user
<where>
username = #{username}
and
password = #{password}
</where>
</select>
<sql id="Base_Column_List">
id,username,password
</sql>
</mapper>
package com.example.harmonyreq.service;
import com.example.harmonyreq.common.Result;
import java.util.Map;
public interface IUserService {
Result login(Map<String,Object> params);
}
package com.example.harmonyreq.service.impl;
import com.example.harmonyreq.common.Result;
import com.example.harmonyreq.mapper.UserMapper;
import com.example.harmonyreq.model.User;
import com.example.harmonyreq.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class UserServiceImpl implements IUserService {
private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private UserMapper userMapper;
@Override
public Result login(Map<String,Object>params) {
Result res = new Result();
try {
User user = userMapper.queryByUnamePwd(params);
if (null!=user){
res.success(user,"成功!");
logger.info("登录成功!");
}else {
res.fail();
}
}catch (Exception e){
logger.error("登录失败!{}",e.getMessage());
res.fail();
return res;
}
return res;
}
}
package com.example.harmonyreq.controller;
import com.example.harmonyreq.common.Result;
import com.example.harmonyreq.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/")
public class LoginController {
private Logger logger = LoggerFactory.getLogger(LoginController.class);
@Autowired
private IUserService userService;
@PostMapping("/login")
public Result login(@RequestBody Map<String,Object>params){
logger.info("请求过来的参数---{}",params);
return userService.login(params);
}
}