赞
踩
赞
踩
写程序最重要的就是数据了,如果没有数据那么程序将毫无意义,其中网络请求就是获得数据的方法!(初学阶段编写)
在src中的main找到module.json5文件中加入以下代码申请网络请求
新建一个utils包存放工具类
具体封装代码如下
- import http from '@ohos.net.http';
- import { Response } from '../model'
- import Preferences from './Preferences';
- //导出httpRequest请求函数
- export async function request(url: string, method: http.RequestMethod, Data?: any): Promise<Response> {
- //基地址
- const BASE_URL: string = "网络请求的基地址"
-
- //获取token值
- let token
- Preferences.getData('token值','token').then((value)=>{
- token = value
- })
-
- //创建http对象
- let httpRequest = http.createHttp()
- let responseResult = httpRequest.request(
- BASE_URL + url,//请求地址
- {
- method: method,//请求方式
- header: {
- 'Content-Type': 'application/json',
- 'Authorization':token//需要携带的token值
- },
- extraData: JSON.stringify(Data), //携带额外参数
- //可选,默认为60000ms
- connectTimeout: 10000, //连接超时时间
- readTimeout: 10000, //读取超时时间
- }
- )
- let response = new Response();
- //处理数据,并返回
- return responseResult.then((value: http.HttpResponse) => {
- if (value.responseCode === 200) {
- //获取返回数据,将返回的json数据解析成事先预定好的响应格式
- //这里建议和后端的保持一致
- let res: Response = JSON.parse(`${value.result}`);
- response.data = res.data;
- response.code = res.code;
- response.msg = res.msg;
- response.token = res.token
- } else {
- response.msg = '请求错误';
- response.code = 400;
- }
- return response;
- }).catch(() => {
- response.msg = '请求错误';
- response.code = 400;
- return response;
- }).finally(() => {
- httpRequest.destroy()
- });
- }
以上代码还缺少几个类的调用在下面我们继续进行编写
在util包下新建Preferences类进行以下代码的编写
- import dataPreferences from '@ohos.data.preferences';
- import promptAction from '@ohos.promptAction';
-
- let context = getContext(this);
- let preference: dataPreferences.Preferences;
- let preferenceTemp: dataPreferences.Preferences;
-
-
- class PreferenceModel {
- /**
- * 读取指定的Preferences持久性文件并将数据加载到Preferences实例中。
- */
- async getPreferencesFromStorage(db_name: string) {
- try {
- preference = await dataPreferences.getPreferences(context, db_name);
- } catch (err) {
- }
- }
-
- /**
- * 删除本地存储
- * 从内存中删除指定的首选项持久性文件,并删除首选项实例。
- */
- async deletePreferences(db_name: string) {
- try {
- await dataPreferences.deletePreferences(context, db_name);
- } catch(err) {
- };
- preference = preferenceTemp;
- }
-
- /**
- * 将数据保存到Preferences中。
- */
- async putPreference(data: any, db_name: string, key: string) {
- if (!preference) {
- await this.getPreferencesFromStorage(db_name);
- }
- // 将用户输入的键值对存入preferences
- try {
- if (typeof data === 'object' && data !== null) {
- await preference.put(key, JSON.stringify(data));
- } else {
- await preference.put(key, data);
- }
- } catch (err) {
- }
- await preference.flush();
- }
-
- /**
- * 取数据
- * 获取首选项数据。
- */
- async getPreference(db_name: string, key: string) {
- let storage;
- if (!preference) {
- await this.getPreferencesFromStorage(db_name);
- }
- try {
- storage = (await preference.get(key, ''));
- } catch (err) {
- }
- // 如果数据为空,则提示需要写数据。
- if (!storage) {
- return '';
- }
- return storage;
- }
-
- /**
- * write data.
- * 存数据
- * @param fruit Fruit data.
- */
- writeData(data: any, db_name: string, key: string) {
- //如果数据不为空,则将数据插入首选项数据库。
- this.putPreference(data, db_name, key);
- console.log(`${db_name}-${key}---writeData成功`)
- }
-
- /**
- * 处理从数据库中获取的数据。
- */
- async getData(db_name: string, key: string) {
- return await this.getPreference(db_name, key);
- }
-
- /**
- * 弹出窗口提示信息。
- *
- * @param message Prompt message.
- */
- showToastMessage(message: Resource) {
- promptAction.showToast({
- message: message,
- duration: 3000
- });
- };
- }
-
- export default new PreferenceModel();
新建一个model包用于存放数据类
- export class Login{
- username:string
- password:string
-
- constructor(username:string,password:string) {
- this.username = username
- this.password = password
- }
- }
将后端常用的数据字段封装起来
- export * from './login/login'
-
-
- export class Response{
- /**
- * 响应码
- */
- code:number
- /**
- * 提示信息
- */
- msg:string
- /**
- * token
- */
- token?:string
- /**
- * 响应数据
- */
- data:any
-
-
- }
- import {request} from '../../utils/request'
- import {Login} from '../../model'
- import http from '@ohos.net.http'
-
- export function login(data:Login){
- return request('url地址',http.RequestMethod.POST,data)
- }
- import router from '@ohos.router'
- import Preferences from '../utils/Preferences'
-
- @Entry
- @Component
- struct Page {
- @State message: string = 'Hello World'
-
- onPageShow() {
- Preferences.getData('token值', 'token').then((value) => {
- if (value != '') {
-
- } else {
- router.pushUrl({
- url: 'pages/Page'
- })
- return
- }
- console.log('This Page is onPageShow')
- })
- }
-
- build() {
- Row() {
- Column() {
- Text(this.message)
- .fontSize(50)
- .fontWeight(FontWeight.Bold)
- Button('点击').width('80%').height(45).onClick(() => {
- Preferences.getData('token值', 'token').then((value) => {
- this.message = value
- })
- })
-
- }
- .width('100%')
- }
- .height('100%')
- }
- }
- import { Login } from '../model'
- import { login } from '../api/login/login'
- import PreferenceModel from '../utils/Preferences'
- import router from '@ohos.router'
- /**
- * 登录页面
- */
- @Entry
- @Component
- struct user{
-
-
- @State user: Login = new Login('','')
-
- @State token:string = ''
-
- build(){
- Column({space: 10}){
- Row(){
- TextInput({placeholder: '请输入账号'})
- .type(InputType.Normal)
- .height(45)
- .backgroundColor('#ffffff')
- .padding(10)
- .layoutWeight(1)
- .onChange(value =>{
- this.user.username = value
- })
- }.padding({left: 20, right: 20})
- Row(){
- TextInput({placeholder: '请输入密码'})
- .type(InputType.PhoneNumber)
- .height(45)
- .backgroundColor('#ffffff')
- .padding({left: 0, right: 0})
- .layoutWeight(1)
- .onChange(value =>{
- this.user.password = value
- })
- }.padding({left: 20, right: 20})
-
- Row(){
- Button('登 录')
- .type(ButtonType.Normal)
- .fontSize(20)
- .width('100%')
- .borderRadius(20)
- .backgroundColor('#2f90b9')
- .fontColor('#ffffff')
- .onClick(() => {
- login(this.user).then(res =>{
- if (res.code === 200) {
-
- PreferenceModel.writeData(res.token,"token值",'token')
-
- router.pushUrl({
- url: 'pages/Index'
- })
- AlertDialog.show({
- title:"成功",
- message: PreferenceModel.getPreference("token值",'token')+''
- })
- } else {
- AlertDialog.show({
- title: '警告',
- message: res.msg
- })
- }
- })
- })
- }.padding({left: 20, right: 20})
-
- }
- .width('100%')
- .height('100%')
- .justifyContent(FlexAlign.Center)
- }
- }
ps:后端接口需要直接弄哦!网上有免费的接口不会写的同学们可以去找一些实训一下
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。