自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

鴻蒙原生應(yīng)用隨機(jī)詩詞

系統(tǒng) OpenHarmony
本文我們學(xué)習(xí)了基礎(chǔ)組件的使用,網(wǎng)絡(luò)請求,以及狀態(tài)管理。希望對你有所幫助!

想了解更多關(guān)于開源的內(nèi)容,請訪問:

51CTO 鴻蒙開發(fā)者社區(qū)

https://ost.51cto.com

運(yùn)行環(huán)境

DAYU200:4.0.10.16

SDK:4.0.10.15

IDE:4.0.600

一、創(chuàng)建應(yīng)用

點(diǎn)擊File->new File->Create Progect。

選擇模版:

【OpenHarmony】Empty Ability:

填寫項目名,shici,應(yīng)用包名com.nut.shici,應(yīng)用存儲位置XXX(不要有中文,特殊字符,空格)。

Compile SDK10,Model :Stage。

Device Type 默認(rèn)就可以。

node,建議16.20.1。

完成以上配置以后點(diǎn)擊Finish。

選擇在新窗口打開,等待依賴加載完畢。如圖所示。

如果大家加載依賴報錯的話,檢查自己的網(wǎng)絡(luò)。

二、運(yùn)行HelloWord

給開發(fā)板供電,并連接開發(fā)板到電腦,如圖所示:

簽名:

簽名的步驟:

點(diǎn)擊File->Project struct。

選擇第三項Signing Configs。

這里我們只勾選Automatically generate就可以,不用勾選Suppot HarmonyOS,因為我們運(yùn)行的是開發(fā)板。

點(diǎn)擊Apply或者ok就可以。

現(xiàn)在點(diǎn)擊按鈕運(yùn)行項目。

控制臺打印信息:

$ 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

證明項目已經(jīng)成功運(yùn)行在開發(fā)板上。

三、修改圖標(biāo)和名稱

修改應(yīng)用圖標(biāo)和名稱:

目錄在AppScope/app.json5。

{
  "app": {
    "bundleName": "com.nut.shici",
    "vendor": "example",
    "versionCode": 1000000,
    "versionName": "1.0.0",
    "icon": "$media:app_icon",
    "label": "$string:app_name"
  }
}

修改完畢之后如圖所示:

修改成功之后,如圖所示:

打開方式,在設(shè)置-應(yīng)用管理一欄。

修改桌面圖標(biāo)和名稱

修改src/main/module.json5中如圖所示的label和icon。

我們修改label的時候,修改中文目錄下的就可以。

{
  "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"
            ]
          }
        ]
      }
    ]
  }
}

修改中文目錄下的。

效果如圖所示:

四、添加相關(guān)權(quán)限

因為需要用到網(wǎng)絡(luò)數(shù)據(jù),所以添加initent權(quán)限。

在src/main/module.json5中modele中添加配置,然后async就可以。

"requestPermissions": [{
      "name": "ohos.permission.INTERNET"
    }],

五、定義數(shù)據(jù)模型

在ets目錄下新建model文件夾。

新建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"
}

六、加載網(wǎng)絡(luò)數(shù)據(jù)

接口說明

準(zhǔn)備好數(shù)據(jù),

接口

接口地址: https://v2.alapi.cn/api/shici

請求方法: [ “GET”, “POST” ]

請求參數(shù):

名稱

必填

類型

描述

示例

token

true

string

請求token,用戶中心獲取。

用戶中心獲取token

format

false

string

返回格式,支持json,text

json

type

string

詩詞類型

all

  • type 參數(shù)值說明
  • all 所有類型
  • shuqing抒情
  • siji四季
  • shanshui山水
  • tianqi天氣
  • renwu人物
  • shenghuo生活
  • jieri節(jié)日
  • dongwu動物
  • zhiwu植物

返回參數(shù):

名稱

描述

content

詩詞內(nèi)容

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"
}

測試如圖所示:

創(chuàng)建HTTP請求

導(dǎo)入http模塊:

import http from '@ohos.net.http';
import { BusinessError } from '@ohos.base';

創(chuàng)建createHttp:

let httpRequest = http.createHttp();

填寫HTTP地址:

httpRequest.request(// 填寫HTTP請求的URL地址,可以帶參數(shù)也可以不帶參數(shù)。URL地址需要開發(fā)者自定義。請求的參數(shù)可以在extraData中指定
      "https://v2.alapi.cn/api/shici",
      {
        method: http.RequestMethod.GET, // 可選,默認(rèn)為http.RequestMethod.GET
        // // 開發(fā)者根據(jù)自身業(yè)務(wù)需要添加header字段
        header: [{
          'Content-Type': 'application/json'
        }],
        // 當(dāng)使用POST請求時此字段用于傳遞內(nèi)容
        extraData: {
          "token": "自己的token",
          "type": "all",
          "format": "json"
        },
   
      }, (err: BusinessError, data: http.HttpResponse) => {
 
    }
    );

對網(wǎng)絡(luò)數(shù)據(jù)的處理:

if (!err) {


        // data.result為HTTP響應(yīng)內(nèi)容,可根據(jù)業(yè)務(wù)需要進(jìn)行解析
        console.info('Result:' + JSON.stringify(data.result));
        console.info('code:' + JSON.stringify(data.responseCode));
        // data.header為HTTP響應(yīng)頭,可根據(jù)業(yè)務(wù)需要進(jìn)行解析
        console.info('header:' + JSON.stringify(data.header));
        console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
        // 當(dāng)該請求使用完畢時,調(diào)用destroy方法主動銷毀
        httpRequest.destroy();
      } else {
        this.message = JSON.stringify(err)
        console.error('error:' + JSON.stringify(err));
        // 取消訂閱HTTP響應(yīng)頭事件
        httpRequest.off('headersReceive');
        // 當(dāng)該請求使用完畢時,調(diào)用destroy方法主動銷毀
        httpRequest.destroy();
      }

完成以上配置以后。

在應(yīng)用程序里測試網(wǎng)絡(luò)請求。

build() {

    Column() {

      Button("測試網(wǎng)絡(luò)請求").onClick(() => {
        this.httpData()
      })
    }.width("100%").height("100%").justifyContent(FlexAlign.Center)
  }
}

如圖所示:

測試成功。

如果2300006錯誤碼,請檢查網(wǎng)絡(luò)。

七、UI

數(shù)據(jù)獲取到之后,我們就剩在頁面上顯示了。

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<shiciType> = [
    { title: "抒情",
      desc: "shuqing"

    },
    { title: "四季",
      desc: "siji"

    },
    { title: "山水",
      desc: "shanshui"

    }
    ,
    { title: "天氣",
      desc: "tianqi"

    }


  ]

  aboutToAppear() {
    this.httpData("all")
  }

  httpData(type: string) {


    // 3.每一個httpRequest對應(yīng)一個HTTP請求任務(wù),不可復(fù)用
    let httpRequest = http.createHttp();
    //4.
    httpRequest.request(// 填寫HTTP請求的URL地址,可以帶參數(shù)也可以不帶參數(shù)。URL地址需要開發(fā)者自定義。請求的參數(shù)可以在extraData中指定
      "https://v2.alapi.cn/api/shici",
      {
        method: http.RequestMethod.GET, // 可選,默認(rèn)為http.RequestMethod.GET
        // // 開發(fā)者根據(jù)自身業(yè)務(wù)需要添加header字段
        header: [{
          'Content-Type': 'application/json'
        }],
        // 當(dāng)使用POST請求時此字段用于傳遞內(nèi)容
        extraData: {
          "token": "你的token",

          "type": type,
          "format": "json"
        },
    
      }, (err: BusinessError, data: http.HttpResponse) => {
      if (!err) {
        // data.result為HTTP響應(yīng)內(nèi)容,可根據(jù)業(yè)務(wù)需要進(jìn)行解析
        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));
       
        // 當(dāng)該請求使用完畢時,調(diào)用destroy方法主動銷毀
        httpRequest.destroy();
      } else {

        console.error('error:' + JSON.stringify(err));
        // 取消訂閱HTTP響應(yīng)頭事件
        httpRequest.off('headersReceive');
        // 當(dāng)該請求使用完畢時,調(diào)用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)
  }
}

九、總結(jié)

本文我們學(xué)習(xí)了基礎(chǔ)組件的使用,網(wǎng)絡(luò)請求,以及狀態(tài)管理。

十、FAQ

2300006 域名解析失敗

錯誤信息

Couldn’t resolve host name。

錯誤描述

服務(wù)器的域名無法解析。

可能原因

  • 傳入的服務(wù)器的URL不正確。
  • 網(wǎng)絡(luò)不通暢。

處理步驟

  • 請檢查輸入的服務(wù)器的URL是否合理。
  • 請檢查網(wǎng)絡(luò)連接情況

想了解更多關(guān)于開源的內(nèi)容,請訪問:

51CTO 鴻蒙開發(fā)者社區(qū)

https://ost.51cto.com

責(zé)任編輯:jianghua 來源: 51CTO 鴻蒙開發(fā)者社區(qū)
相關(guān)推薦
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號