To learn more about open source, please visit:
51CTO Hongmeng Developer Community
https://ost.51cto.com
Running environment
DAYU200:4.0.10.16
SDK:4.0.10.15
IDE:4.0.600
1. Create an application
Click File->new File->Create Progect.
Select template:
【OpenHarmony】Empty Ability:
Fill in the project name, shici, application package name com.nut.shici, and application storage location XXX (no Chinese, special characters, or spaces).
Compile SDK10, Model: Stage.
Device Type is fine by default.
node, 16.20.1 is recommended.
After completing the above configuration, click Finish.
Choose to open in a new window and wait for the dependencies to be loaded. as the picture shows.
If you get an error when loading dependencies, check your network.
2. Run HelloWord
Power the development board and connect the development board to the computer, as shown in the figure:
sign:
Steps to sign:
Click File->Project struct.
Select the third item Signing Configs.
Here we only need to check Automatically generate. We do not need to check Support HarmonyOS because we are running a development board.
Click Apply or OK.
Now click the button to run the project.
Console printing information:
$ hdc uninstall com.nut.shici $ hdc shell mkdir data/local/tmp/a1bdb2dbe1724c67a1106c360a3f1d35 $ hdc file send "/Users/jianguo/Desktop/teaching/ohcode/shici/entry/build/default/outputs/default/entry-default-signed.hap" "data/local/tmp/a1bdb2dbe1724c67a1106c360a3f1d35" $ hdc shell bm install -p data/local/tmp/a1bdb2dbe1724c67a1106c360a3f1d35 $ hdc shell rm -rf data/local/tmp/a1bdb2dbe1724c67a1106c360a3f1d35 $ hdc shell aa start -a EntryAbility -b com.nut.shici
Proof that the project has been successfully run on the development board.
3. Modify the icon and name
Modify application icon and name:
The directory is in AppScope/app.json5.
{ "app": { "bundleName": "com.nut.shici", "vendor": "example", "versionCode": 1000000, "versionName": "1.0.0", "icon": "$media:app_icon", "label": "$string:app_name" } }
As shown in the figure after modification:
After the modification is successful, as shown in the figure:
Open method, in the Settings-Application Management column.
Modify desktop icons and names
Modify the label and icon in src/main/module.json5 as shown in the figure.
When we modify the label, we just need to modify it in the Chinese directory.
{ "module": { "name": "entry", "type": "entry", "description": "$string:module_desc", "mainElement": "EntryAbility", "deviceTypes": [ "default", "tablet" ], "deliveryWithInstall": true, "installationFree": false, "pages": "$profile:main_pages", "abilities": [ { "name": "EntryAbility", "srcEntry": "./ets/entryability/EntryAbility.ets", "description": "$string:EntryAbility_desc", "icon": "$media:icon", "label": "$string:EntryAbility_label", "startWindowIcon": "$media:startIcon", "startWindowBackground": "$color:start_window_background", "exported": true, "skills": [ { "entities": [ "entity.system.home" ], "actions": [ "action.system.home" ] } ] } ] } }
Modify the Chinese directory.
The effect is as shown in the figure:
4. Add relevant permissions
Because network data is needed, add the intent permission.
Add configuration in modele in src/main/module.json5, and then async.
"requestPermissions": [{ "name": "ohos.permission.INTERNET" }],
5. Define the data model
Create a new model folder in the ets directory.
Create a new TS File.
export class ShiciModel { code: number = 0 message: string = "" data: ShiCi = new ShiCi() } export class ShiCi { content: string = "" author: string = "" origin: string = "" category: string = "" c1: string = "" c2: string = "" c3: string = "" // "content": "微雨过,小荷翻。榴花开欲然。", // "author": "苏轼", // "origin": "阮郎归·初夏", // "category": "古诗文-植物-荷花", // "c1": "gushiwen", // "c2": "zhiwu", // "c3": "hehua" }
6. Load network data
Interface Description
Prepare the data,
interface
Interface address: https://v2.alapi.cn/api/shici
Request method: [ “GET”, “POST” ]
Request parameters:
name |
Required |
type |
describe |
Example |
token |
true |
string |
Request token and obtain it from the user center. |
User center gets token |
format |
false |
string |
返回格式,支持json,text |
json |
type |
string |
诗词类型 |
all |
- type 参数值说明
- all 所有类型
- shuqing抒情
- siji四季
- shanshui山水
- tianqi天气
- renwu人物
- shenghuo生活
- jieri节日
- dongwu动物
- zhiwu植物
返回参数:
名称 |
描述 |
content |
诗词内容 |
author |
作者 |
origin |
诗词题 |
测试接口
测试工具:Postamn。
{ "code": 200, "msg": "success", "data": { "content": "地冷叶先尽,谷寒云不行。", "author": "李白", "origin": "冬日归旧山", "category": "古诗文-植物-叶子", "c1": "gushiwen", "c2": "zhiwu", "c3": "yezi" }, "time": 1704770459, "usage": 0, "log_id": "603184784204148736" }
测试如图所示:
创建HTTP请求
导入http模块:
import http from '@ohos.net.http'; import { BusinessError } from '@ohos.base';
创建createHttp:
let httpRequest = http.createHttp();
填写HTTP地址:
httpRequest.request(// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 "https://v2.alapi.cn/api/shici", { method: http.RequestMethod.GET, // 可选,默认为http.RequestMethod.GET // // 开发者根据自身业务需要添加header字段 header: [{ 'Content-Type': 'application/json' }], // 当使用POST请求时此字段用于传递内容 extraData: { "token": "自己的token", "type": "all", "format": "json" }, }, (err: BusinessError, data: http.HttpResponse) => { } );
对网络数据的处理:
if (!err) { // data.result为HTTP响应内容,可根据业务需要进行解析 console.info('Result:' + JSON.stringify(data.result)); console.info('code:' + JSON.stringify(data.responseCode)); // data.header为HTTP响应头,可根据业务需要进行解析 console.info('header:' + JSON.stringify(data.header)); console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ // 当该请求使用完毕时,调用destroy方法主动销毁 httpRequest.destroy(); } else { this.message = JSON.stringify(err) console.error('error:' + JSON.stringify(err)); // 取消订阅HTTP响应头事件 httpRequest.off('headersReceive'); // 当该请求使用完毕时,调用destroy方法主动销毁 httpRequest.destroy(); }
完成以上配置以后。
在应用程序里测试网络请求。
build() { Column() { Button("测试网络请求").onClick(() => { this.httpData() }) }.width("100%").height("100%").justifyContent(FlexAlign.Center) } }
如图所示:
测试成功。
如果2300006错误码,请检查网络。
七、UI
数据获取到之后,我们就剩在页面上显示了。
U I布局如图所示。
build() { Column() { Text(this.shici.origin).fontSize(30).fontWeight(800) Text(this.shici.author).fontSize(20).fontWeight(300).fontColor(Color.Orange) Text(this.shici.category).fontSize(20).fontWeight(300).fontColor(Color.Green) }.width("100%").height("100%").justifyContent(FlexAlign.Center) }
八、完整源码
import http from '@ohos.net.http'; import { BusinessError } from '@ohos.base'; import promptAction from '@ohos.promptAction'; import { ShiCi, ShiciModel } from '../../model/ShiCiModel'; class shiciType { title: string = "" desc: string = "" } @Entry @Component struct Index { @State shici: ShiCi = new ShiCi() @State typeList: Array = [ { title: "抒情", desc: "shuqing" }, { title: "四季", desc: "siji" }, { title: "山水", desc: "shanshui" } , { title: "天气", desc: "tianqi" } ] aboutToAppear() { this.httpData("all") } httpData(type: string) { // 3.每一个httpRequest对应一个HTTP请求任务,不可复用 let httpRequest = http.createHttp(); //4. httpRequest.request(// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 "https://v2.alapi.cn/api/shici", { method: http.RequestMethod.GET, // 可选,默认为http.RequestMethod.GET // // 开发者根据自身业务需要添加header字段 header: [{ 'Content-Type': 'application/json' }], // 当使用POST请求时此字段用于传递内容 extraData: { "token": "你的token", "type": type, "format": "json" }, }, (err: BusinessError, data: http.HttpResponse) => { if (!err) { // data.result为HTTP响应内容,可根据业务需要进行解析 console.info('Result:' + JSON.stringify(data.result)); let ShiciModel: ShiciModel = JSON.parse(data.result.toString()) this.shici = ShiciModel.data console.info('code:' + JSON.stringify(data.responseCode)); // 当该请求使用完毕时,调用destroy方法主动销毁 httpRequest.destroy(); } else { console.error('error:' + JSON.stringify(err)); // 取消订阅HTTP响应头事件 httpRequest.off('headersReceive'); // 当该请求使用完毕时,调用destroy方法主动销毁 httpRequest.destroy(); } } ); } build() { Column() { Row() { ForEach(this.typeList, (item: shiciType) => { Text(item.title).fontSize(30).margin(20) .onClick(() => { this.httpData(item.desc) }) }) } Button( "抒情" ).onClick(() => { this.httpData("shuqing") }) Button( "四季" ).onClick(() => { this.httpData("siji") }) Text(this.shici.origin).fontSize(30).fontWeight(800) Text(this.shici.author).fontSize(20).fontWeight(300).fontColor(Color.Orange) Text(this.shici.category).fontSize(20).fontWeight(300).fontColor(Color.Green) }.width("100%").height("100%").justifyContent(FlexAlign.Center) } }
九、总结
本文我们学习了基础组件的使用,网络请求,以及状态管理。
十、FAQ
2300006 域名解析失败
错误信息
Couldn’t resolve host name。
错误描述
服务器的域名无法解析。
可能原因
- 传入的服务器的URL不正确。
- 网络不通畅。
处理步骤
- 请检查输入的服务器的URL是否合理。
- 请检查网络连接情况
想了解更多关于开源的内容,请访问:
51CTO 鸿蒙开发者社区
https://ost.51cto.com
The above is the detailed content of Hongmeng native application random poetry. For more information, please follow other related articles on the PHP Chinese website!

The tabs feature in File Explorer is a highly convenient function for Windows users, yet it is not available on Windows 10. Nevertheless, you can enable tabs in File Explorer on Windows using third-party apps like Files. In this post, php.cn Software

Windows provides an option to hide the taskbar automatically when you’re not using it. However, some users report that they meet the “auto-hide taskbar not working in Windows 11” issue. This post from php.cn provides solutions.

Have you ever encountered the error message saying “install Realtek audio driver failure error code 0001” while trying to install a Realtek audio driver? If yes, you’ve come to the right place. This post on php.cn Software explains how to get this pr

Windows Firewall notification keeps popping up? How to turn off Windows Firewall notifications? Now, you can get three proven ways from this post on php.cn to prevent Firewall notifications from popping up.

Want to sell or throw away your external drive but worried about data leakage? Deleted external hard drive files keep reappearing? How to permanently delete files from external hard drive? This post on php.cn shows you secure ways to delete external

Computer users may encounter high CPU usage problems even if they don’t run too many programs on computers. Sometimes this problem can be fixed automatically, however, in some cases, you need to fix the problem manually, such as Network List Service

A USB flash drive works as the most commonly used data storage device nowadays. However, it is easy to be infected by various viruses because you connect it to different devices to transfer files. When you find your USB files turned into EXE files, y

Windows 11 desktop background keeps changing and whenever you customize the wallpaper settings, Windows 11 will revert the changes. That is annoying and this article on the php.cn Website will present some methods that have been proven to be useful f


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use