????????應用通過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)}
}