团队介绍
作者:徐庆
团队:坚果派 公众号:"大前端之旅" 润开鸿生态技术专家,华为HDE,CSDN博客专家,CSDN超级个体,CSDN特邀嘉宾,InfoQ签约作者,OpenHarmony布道师,电子发烧友专家博客,51CTO博客专家,擅长HarmonyOS/OpenHarmony应用开发、熟悉服务卡片开发。欢迎合作。
前言:
各位同学有段时间没有见面 因为一直很忙所以就没有去更新博客。最近有在学习这个鸿蒙的ark ui开发 因为鸿蒙不是发布了一个鸿蒙next的测试版本 明年会启动纯血鸿蒙应用 所以我就想提前给大家写一些博客文章 今天要讲的是请求网络数据并显示到listview

添加网络权限
json
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]

具体实现:
1 定义数据模型
ini
export class MenuModel {
ret: string = ""
data: Array<ShiCi> = []
}
export class ShiCi {
id: string = ""
title: string = ""
pic: string = ""
collect_num: string = ""
food_str: string = ""
num: string = ""
}
2 加载网络数据
接口地址 www.qubaobei.com/ios/cf/dish... 请求参数
名称 | 必填 | 类型 | 描述 | 示例 |
---|---|---|---|---|
stage_id | true | string | 条件参数 | |
limit | true | string | 每一页显示多少条 | |
page | true | string | 页码 |

网络请求封装
typescript
import http from '@ohos.net.http';
import Constants, { ContentType } from '../common/constant/Constants';
import Logger from './Logger';
export function httpRequestGet(url: string) {
return httpRequest(url, http.RequestMethod.GET);
}
/*export function httpRequestGet(url: string, params?:string) {
return httpRequest(url, http.RequestMethod.GET,params);
}*/
export function httpRequestPost(url: string, params?:string ) {
return httpRequest(url, http.RequestMethod.POST, params);
}
function httpRequest(url: string, method: http.RequestMethod,params?: string){
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 // 请求参数
});
return responseResult.then((value: http.HttpResponse)=>{
Logger.error("请求状态 --> "+value.responseCode)
if(value.responseCode===200){
Logger.error("请求成功");
let getresult = value.result;
Logger.error('请求返回数据', JSON.stringify(getresult));
return getresult;
}
}).catch((err)=>{
httpRequest.off('headersReceive');
// 当该请求使用完毕时,调用destroy方法主动销毁
httpRequest.destroy();
return "";
});
}
日志工具类
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 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)
在UI中调用工具类请求网络
- 因为我们一进去就要请求网络 所以会我们要在 aboutToAppear 方法中进行
javascript
async aboutToAppear(){
Logger.error(this.TAG+' aboutToAppear --- > ');
let networkurl=CommonConstant.MENU;
await httpRequestGet(networkurl).then((data)=>{
console.log("data --- > "+data);
Logger.error("登录请求回调结果 ---> " +data.toString());
let menuModel: MenuModel = JSON.parse(data.toString())
this.JokeList = menuModel.data
});
}
解析json将我们的json数据转换成一个对象然后复制给我们的 menuModel 我们取到里面的 JokeList 赋值我们的成员变量的 JokeList
kotlin
this.JokeList = menuModel.data
我们就可以在我们的build里面去使用数据加载到list各个UI组件中 (这里因为我们接口返回的图片的url访问不了我就找了一张其他图片 代替 这里写法差异不大 大家需要注意 )
然后在我们的build中显示加载数据到list组件里面去
scss
build() {
Row() {
List({ space: commonConst.LIST_ITEM_SPACE }) {
ForEach(this.JokeList, (item) => {
ListItem() {
Row() {
Column() {
Image('https://www.itying.com/images/flutter/2.png')
.width(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
.height(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
}
.width(commonConst.GOODS_IMAGE_WIDTH)
.height(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
Column() {
Text(item?.title)
.fontSize(commonConst.NORMAL_FONT_SIZE)
.margin({ bottom: commonConst.BIGGER_FONT_SIZE })
Text(item?.food_str)
.fontColor($r('app.color.gray'))
.fontSize(commonConst.GOODS_EVALUATE_FONT_SIZE)
.margin({ right: commonConst.MARGIN_RIGHT, bottom: commonConst.BIGGER_FONT_SIZE })
Text('喜欢人数:'+item?.num)
.fontColor($r('app.color.gray'))
.fontSize(commonConst.GOODS_EVALUATE_FONT_SIZE)
.margin({ right: commonConst.MARGIN_RIGHT, bottom: commonConst.BIGGER_FONT_SIZE })
}
.padding(commonConst.GOODS_LIST_PADDING)
.width(commonConst.GOODS_FONT_WIDTH)
.height(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
}
.justifyContent(FlexAlign.SpaceBetween)
.height(commonConst.GOODS_LIST_HEIGHT)
.width(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
}
})
}
.width(commonConst.GOODS_LIST_WIDTH)
}
.justifyContent(FlexAlign.Center)
.width(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
}
最终效果图

最后总结:
整个网络请求和json解析和我们Android还有Flutter都非常像, 需要创建一个model类然后接收 ,请求的时机要是跟我们安卓和Flutter很像需要根据视图的生命周期方法来处理。比较好理解 那么今天的文章就讲到这里 有兴趣的同学可以对照文章进行学习和扩展。最后呢 希望我都文章能帮助到各位同学工作和学习 如果你觉得文章还不错麻烦给我三连 关注点赞和转发 谢谢