鴻蒙 harmonyOS 網絡請求

????????應用通過HTTP發起一個數據請求,支持常見的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。

接口說明

????????HTTP數據請求功能主要由http模塊提供。

????????使用該功能需要申請ohos.permission.INTERNET權限。

第一步 :

????????在module.json5文件里面添加網絡請求。

//網絡請求
"requestPermissions": [{"name": "ohos.permission.INTERNET"
}]

第二步:

????????在要使用網絡模塊的地方導入HTTP模塊。

//導入HTTP模塊import { http } from "@kit.NetworkKit"

第三步:

????????創建網絡請求模塊。


//創建請求模塊const req = http.createHttp()

第四步:

? ? ? ? 創建請求網絡數據方法。

//請求網絡數據  
get_HotData() {req.request(Hot_url + '/list_hot', {method: http.RequestMethod.GET //數據請求為GET模式}).then(res1 => {let _data1 = (JSON.parse(res1.result.toString()) as HotData).data;this.allData = _data1.hot;// 將_data.hot中的title單獨拿出來for (let i = 0; i < this.allData.length; i++) {this.titles.push(this.allData[i].title)}this.hotList1 = this.allData[0].list;this.hotList2 = this.allData[1].list;console.log(JSON.stringify(this.titles)); //成功拿到標題數據console.log(JSON.stringify(this.hotList1)); //成功拿到熱門精選數據console.log(JSON.stringify(this.hotList2)); //成功拿到熱門品牌數據})}

第五步:

????????創建調用HTTP模塊的方法。

 //調用HTTP請求aboutToAppear() {this.get_HotData()}

代碼展示:

Home.ets文件內容

//網絡導包
import { http } from '@kit.NetworkKit'
import { hot } from '../Hot_Recommend/Hot'//創建網絡請求
const req = http.createHttp()
//構建網絡數據接口
const HTTP_url = 'https://mock.mengxuegu.com/mock/67cfd2b76e797f1d6cbe2e9b/data_exmaple'//構建介紹數據格式的接口
interface QuanBu {data: DataNew
}interface DataNew {banner: Array<ResourceStr>,menus: Array<XianXi>
}interface XianXi {icon: ResourceStr,title: string
}@Entry
@Component
struct Home {//創建狀態變量用于儲存數據@State banner_list: Array<ResourceStr> = [];@State menus_list: Array<XianXi> = [];//請求網絡數據getHomeData() {req.request(HTTP_url + '/home', {method: http.RequestMethod.GET}).then(res => {let _data = (JSON.parse(res.result.toString()) as QuanBu).data;// 將獲取的數據給狀態變量this.banner_list = _data.banner;this.menus_list = _data.menus;//打印測試是否拿到數據console.log(JSON.stringify(this.banner_list))console.log(JSON.stringify(this.menus_list))})}//調用HTTP請求aboutToAppear() {this.getHomeData()}build() {Scroll(){Column(){//輪播圖部分Swiper() {ForEach(this.banner_list, (item: ResourceStr) => {Image(item).width('100%').borderRadius(10)})}.autoPlay(true).width('100%').height(170)//列表部分Grid() { //使用網格布局ForEach(this.menus_list, (item: XianXi) => {GridItem() {Column({ space: 10 }) {Image(item.icon).width(50).height(40)Text(item.title).fontSize(14)}.width('100%').height(50)}})}.margin({top:15})//給上面一點外邊距.columnsTemplate('1fr 1fr 1fr 1fr 1fr') //5/列.rowsTemplate('1fr 1fr ') //2行.columnsGap(1).rowsGap(10).height(180)//熱門部分Column(){hot()}.width('100%')}.width('90%')}.edgeEffect(EdgeEffect.Spring).scrollBar(BarState.Off).width('100%')}
}

Hot.ets 文件內容

//導入HTTP模塊
import { http } from "@kit.NetworkKit"//創建請求模塊
const req = http.createHttp()
//構建網絡數據接口
const Hot_url = 'https://mock.mengxuegu.com/mock/67cfd2b76e797f1d6cbe2e9b/data_exmaple'//構建數據接口
interface HotData {data: Hot
}interface Hot {hot: Array<HotList>
}interface HotList {title: stringlist: Array<ListItem>
}interface ListItem {title: stringimg: ResourceStrintr: stringprice: numbernum?: numberfig?: boolean
}@Component
export struct hot {//創建狀態變量用于接受數據// 所有數據的容器@State allData: Array<HotList> = []// 定義title數組容器@State titles: Array<string> = []// 定義熱門精選的列表@State hotList1: Array<ListItem> = []// 定義熱門品牌的列表@State hotList2: Array<ListItem> = []//定義當前被選擇的Tab按鈕的索引@State current:number=0//請求網絡數據get_HotData() {req.request(Hot_url + '/list_hot', {method: http.RequestMethod.GET //數據請求為GET模式}).then(res1 => {let _data1 = (JSON.parse(res1.result.toString()) as HotData).data;this.allData = _data1.hot;// 將_data.hot中的title單獨拿出來for (let i = 0; i < this.allData.length; i++) {this.titles.push(this.allData[i].title)}this.hotList1 = this.allData[0].list;this.hotList2 = this.allData[1].list;console.log(JSON.stringify(this.titles)); //成功拿到標題數據console.log(JSON.stringify(this.hotList1)); //成功拿到熱門精選數據console.log(JSON.stringify(this.hotList2)); //成功拿到熱門品牌數據})}//調用HTTP請求aboutToAppear() {this.get_HotData()}build() {Column() {Row({ space: 15 }) {Tabs() {TabContent() {this.tabs1()}.tabBar(this.TabBuilder(0,'熱門精選'))TabContent() {this.tabs2()}.tabBar(this.TabBuilder(1,'熱門品牌'))}.onChange((index)=>{this.current=index})}}.padding(5)}//自定義Tabs組件@Builder TabBuilder(index:number ,title:string){Text(title).padding({bottom:10}).fontWeight(this.current===index?700:500).fontSize(this.current===index?20:16).border(this.current===index?{width:{bottom:4} ,color:Color.Red}:{width:0})}//熱門精選@Buildertabs1() {//用瀑布流循環輸出WaterFlow() {ForEach(this.hotList1, (item: ListItem) => {FlowItem() {Column({ space: 5 }) {Image(item.img).width(140).height(140).objectFit(ImageFit.Auto)Row() {Text(item.title).fontWeight(700).fontSize(14)Text('¥' + item.price.toFixed(2)).fontSize(14).fontWeight(700)}.width(140).justifyContent(FlexAlign.SpaceBetween)Text(item.intr).fontSize(14).maxLines(2).textOverflow({ overflow: TextOverflow.Ellipsis }).width(140)}.width(150).border({width:1,color:Color.Grey}).padding(5).borderRadius(5)}})}.layoutWeight(1).width('100%').columnsTemplate('1fr 1fr').columnsGap(10).rowsGap(10)}//熱門品牌@Buildertabs2() {//用瀑布流循環輸出WaterFlow() {ForEach(this.hotList2, (item: ListItem) => {FlowItem() {Column({ space: 5 }) {Image(item.img).width(140).height(140).objectFit(ImageFit.Auto)Row() {Text(item.title).fontWeight(700).fontSize(14)Text('¥' + item.price.toFixed(2)).fontSize(14).fontWeight(700)}.width(140).justifyContent(FlexAlign.SpaceBetween)Text(item.intr).fontSize(14).maxLines(2).textOverflow({ overflow: TextOverflow.Ellipsis }).width(140)}.width(150).border({width:1}).padding(5).borderRadius(5)}})}.width('100%').columnsTemplate('1fr 1fr').columnsGap(10).rowsGap(10)}
}

效果圖展示:

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/76173.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/76173.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/76173.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ICMP 協議深度解析

ICMP 協議深度解析 一、協議定位與核心作用 ICMP&#xff08;互聯網控制報文協議&#xff09;是IP協議體系的"哨兵系統"&#xff0c;專用于網絡狀態監控與異常反饋。其核心價值體現在&#xff1a; 輕量級控制&#xff1a;僅傳遞關鍵狀態信息&#xff0c;不承載業務…

【設計模式】模板模式

簡介 假設你要沖泡咖啡和茶&#xff0c;兩者的流程相似但部分步驟不同&#xff1a; 燒水&#xff08;公共步驟&#xff09;加入主材料&#xff08;咖啡粉/茶葉&#xff09;添加調料&#xff08;糖/牛奶&#xff09;→ 可選步驟倒進杯子&#xff08;公共步驟&#xff09; 模板…

【學Rust寫CAD】37 premultiply 函數(argb.rs補充方法)

源碼 fn premultiply(self) -> Argb {//預乘// This could be optimized by using SWARlet a self.alpha32();if a < 255 {Argb::new32(a, div255(self.red32() * a), div255(self.green32() * a),div255(self.blue32() * a))}else{self}源碼分析 這個函數實現了顏色預…

Redis-一般操作

1.redis命令CRUG網站 2.string 、 hash 、list 、 set 、zset 3.4種應用(對象存儲、累加器、分布式鎖、位運算) 1.redis命令CRUG網站 2string 、 hash 、list 、 set 、zset 3.4種應用(對象存儲、累加器、分布式鎖、位運算) 1.redis命令CRUG網站 #1.啟動redis redis-server r…

Vue 基礎語法介紹

Vue.js 是一個漸進式的 JavaScript 框架&#xff0c;廣泛用于構建用戶界面和單頁應用&#xff08;SPA&#xff09;。它的核心思想是通過簡單的模板語法和響應式的數據綁定機制&#xff0c;使得開發者能夠更直觀地創建動態交互的網頁。本文將介紹 Vue.js 的一些基礎語法&#xf…

Flask + Pear Admin Layui 快速開發管理后臺

框架介紹 Flask 就不用過多介紹了, Pear Admin Layui 是基于 Layui 的一套管理后臺前端開源模板, 主打一個開箱即用, 對于不喜歡 React/Vue 等這些還需要大量學習成本的前端開發者來說, 可以說是相當友好了. 項目官網: https://gitee.com/pear-admin/pear-admin-layui 項目的作…

git push

在 git push 命令中&#xff0c;分支名稱的順序和含義非常重要。其基本格式如下&#xff1a; git push <remote> <local_branch>:<remote_branch>各部分解釋 <remote>&#xff1a;遠程倉庫的名稱&#xff08;如 origin&#xff09;。<local_branc…

wordpress 利用 All-in-One WP Migration全站轉移

導出導入站點 在插件中查詢 All-in-One WP Migration備份并導出全站數據 導入 注意事項&#xff1a; 1.導入部分限制50MB 寶塔解決方案&#xff0c;其他類似&#xff0c;修改php.ini配置文件即可 2. 全站轉移需要修改域名 3. 大文件版本&#xff0c;大于1G的可以參考我的…

藍橋杯補題

方法技巧&#xff1a; 1.進行循環暴力騙分&#xff0c;然后每一層的初始進行判斷&#xff0c;如果已經不滿足題意了&#xff0c;那么久直接continue&#xff0c;后面的循環就不用浪費時間了。我們可以把題目所給的等式&#xff0c;比如說有四個未知量&#xff0c;那么我們可以用…

MySQL:鎖

按粒度分類 全局鎖 含義&#xff1a;全局鎖會鎖定整個數據庫實例&#xff0c;在其生效期間&#xff0c;其他事務無法對數據庫進行任何讀寫操作。常用于數據遷移、數據備份場景。 表級鎖 表鎖&#xff1a;是對整張表進行鎖定的機制。實現邏輯簡單&#xff0c;加鎖和釋放鎖速…

數字政府政務服務領域智能化應用解決方案

數字政府政務服務領域智能化應用 解決方案 一、方案背景 在數字經濟蓬勃發展的當下&#xff0c;數字化轉型已成為政府提升治理能力、優化公共服務、增強競爭力的關鍵路徑。黨的十九屆四中全會明確提出 “推進數字政府建設”&#xff0c;這為政府的數字化轉型指明了方向。 隨…

03--Deepseek服務器部署與cjson解析

一、ollama部署deepseek模型 1、Ollama 是一個開源的本地大語言模型運行框架&#xff0c;專為在本地機器上便捷部署和運行大型語言模型&#xff08;LLM&#xff09;而設計。 Ollama 教程&#xff1a;從 0 到 1 全面指南 教程【全文兩萬字保姆級詳細講解】 -CSDN博客 1.下載o…

棧(算法)

在 C 里&#xff0c;棧是一種遵循后進先出&#xff08;LIFO&#xff09;原則的數據結構。下面從多個方面為你介紹 C 棧&#xff1a; 1. 使用標準庫中的std::stack C 標準庫提供了std::stack容器適配器&#xff0c;能方便地實現棧的功能。以下是簡單示例&#xff1a; cpp #in…

UniApp 頁面布局自定義頭部導航

動態計算頭部高度與內容偏移量&#xff1a;實現 UniApp 頁面布局的精準適配 在移動端應用開發中&#xff0c;頁面布局的精準適配是一個關鍵問題。尤其是在 UniApp 中&#xff0c;不同設備的屏幕尺寸、狀態欄高度以及頭部布局的差異&#xff0c;可能導致頁面內容錯位或顯示不全…

verilog學習--1、語言要素

先看一個例子 /*This is first Verilog progaram*/ timescale 1ns/1ns module HalfAdder(A,B,Sum,Carry);input A,B;output Sum, Carry; /**/assign #2 SumA^B;assign #5 CarryA&B&#xff1b; endmodule; Verilog以module為單位編寫&#xff0c;每個文件一個module&#…

AC 自動機 洛谷P3808 P3796 P5357

洛谷P3808 #include <bits/stdc.h> using namespace std; const int maxn 1e6 5; int ch[maxn][30], fa[maxn], End[maxn]; int cnt 0 , n; int get_num(char c){return c - a;} void build(string s){int cur 0, len s.length();for(int i 0; i < len; i){int…

C++藍橋杯實訓篇(二)

片頭 嗨咯~小伙伴們&#xff01;今天我們來一起學習算法和貪心思維&#xff0c;準備好了嗎&#xff1f;咱們開始咯&#xff01; 第1題 數位排序 對于這道題&#xff0c;我們需要自己寫一個排序算法&#xff0c;也就是自定義排序&#xff0c;按照數位從小到大進行排序。 舉一…

redisson常用加鎖方式

RLock lock redissonClient.getLock("lock:order:" order);和redissonDistributedLocker.tryLock("lock:order:" order&#xff0c; TimeUnit.SECONDS, RedisLockKey.DEFAULT_WAIT_TIME, RedisLockKey.DEFAULT_HOLD_TIME);這兩種加鎖方式的區別如下&…

Go 微服務框架 | 路由實現

文章目錄 不用框架實現web接口實現簡單的路由實現分組路由支持不同的請求方式支持同一個路徑的不同請求方式前綴樹應用前綴樹完善路由代碼 不用框架實現web接口 // blog main.go 文件 package mainimport ("fmt""log""net/http" )func main() {…

zabbix中通過模板實現自動發現對tcp端口批量監控

主要為了解決監控大量端口&#xff0c;避免繁瑣的重復操作監控項和觸發器 諸位~ 僅供參考哈 自動發現監控參考地址: https://blog.csdn.net/qq_37510195/article/details/130893655 模板 首先創建一個模板 自定義名稱和群組 創建自動發現規則 模板——自動發現——創建發現規則…