import http from '@ohos.net.http'
@Entry
@Component
struct HttpPage {@State message: string = 'Hello World'build() {Column({space:20}) {Row(){Button('發送http請求').onClick(()=>{let httpRequest = http.createHttp();httpRequest.request('https://zzgoodqc.cn/index.php/index/qus/getquestionlist',{method:http.RequestMethod.POST,extraData:{sn:'1001'}}).then(resp=>{console.log("resp=>",JSON.stringify(resp))if(resp.responseCode === 200){console.log(resp.result.toString())}}).catch(err=>{console.log('請求錯誤err=>',err)})})}}.width('100%').height('100%')}
}
以上是方案1:默認數據請求
方案二:使用axios第三方庫請求接口
第一步:安裝aixos,執行
ohpm install @ohos/axios
第二步:注意配置網絡權限,在module.json5文件中
"requestPermissions":[{"name": "ohos.permission.INTERNET"}],
第三步:類似vue,正常引入使用
import axios from '@ohos/axios'
@Entry
@Component
struct HttpPage {@State message: string = 'Hello World'build() {Column({space:20}) {Row(){Button('發送axios請求').onClick(()=>{axios.post('https://zzgoodqc.cn/index.php/index/qus/getquestionlist',{sn:'1001'}).then(response=>{console.log("response=>",JSON.stringify( response))}).catch(err=>{console.log('err=>',err)})})}}.width('100%').height('100%')}
}