HarmonyOS 平臺中使用網絡請求,需要引入 "@ohos.net.http", 并且需要在 module.json5 文件中申請網絡權限, 即 “ohos.permission.INTERNET”
本篇文章將嘗試使用 @ohos.net.http 來實現網絡請求
場景設定
- WeiBo UniDemo HuaWei : 請求順序
- WeiBo1 UniDemo2 HuaWei3 : 異步/同步請求時,序號表示請求回來的順序
- “開始網絡請求-異步” : 開始異步請求
- “開始網絡請求-同步” : 開始同步請求
- “開始網絡請求-自定義方法裝飾器” : 采用自定義方法裝飾器進行傳參,進而完成網絡請求
官方網絡請求案例
注意:
每次請求都必須新創建一個HTTP請求實例,即只要發起請求,必須調用createHttp方法
更多鴻蒙開發應用知識已更新qr23.cn/AKFP8k
參考前往。
關于 @ohos.net.http 有三個request方法
可+mau123789獲取鴻蒙文檔
- request(url: string, callback: AsyncCallback): void;
1.1 如下“官方指南代碼縮減版”使用到了這個方法 - request(url: string, options: HttpRequestOptions, callback: AsyncCallback): void;
2.1 如下“官方指南代碼” 使用了這個方法 - request(url: string, options?: HttpRequestOptions): Promise;
3.1 將在后續實踐代碼中使用到
// 引入包名
import http from '@ohos.net.http';
// 每一個httpRequest對應一個HTTP請求任務,不可復用
let httpRequest = http.createHttp();
// 用于訂閱HTTP響應頭,此接口會比request請求先返回。可以根據業務需要訂閱此消息
// 從API 8開始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (header) = > {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// 填寫HTTP請求的URL地址,可以帶參數也可以不帶參數。URL地址需要開發者自定義。請求的參數可以在extraData中指定
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // 可選,默認為http.RequestMethod.GET
// 開發者根據自身業務需要添加header字段
header: {
'Content-Type': 'application/json'
},
// 當使用POST請求時此字段用于傳遞內容
extraData: {
"data": "data to send",
},
expectDataType: http.HttpDataType.STRING, // 可選,指定返回數據的類型
usingCache: true, // 可選,默認為true
priority: 1, // 可選,默認為1
connectTimeout: 60000, // 可選,默認為60000ms
readTimeout: 60000, // 可選,默認為60000ms
usingProtocol: http.HttpProtocol.HTTP1_1, // 可選,協議類型默認值由系統自動指定
}, (err, data) = > {
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+
} else {
console.info('error:' + JSON.stringify(err));
// 取消訂閱HTTP響應頭事件
httpRequest.off('headersReceive');
// 當該請求使用完畢時,調用destroy方法主動銷毀
httpRequest.destroy();
}
}
);
// 引入包名
import http from '@ohos.net.http';
// 每一個httpRequest對應一個HTTP請求任務,不可復用
let httpRequest = http.createHttp();
httpRequest.request(
// 填寫HTTP請求的URL地址,可以帶參數也可以不帶參數。URL地址需要開發者自定義。請求的參數可以在extraData中指定
"EXAMPLE_URL",
(err, data) = > {
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+
} else {
console.info('error:' + JSON.stringify(err));
// 取消訂閱HTTP響應頭事件
httpRequest.off('headersReceive');
// 當該請求使用完畢時,調用destroy方法主動銷毀
httpRequest.destroy();
}
}
);
場景布局
基礎頁面組件代碼
考慮到實際的場景會用到網絡請求加載,因此這里將發揮 [@BuilderParam] 裝飾器作用,先定義基礎頁面
組件中定義了 @Prop netLoad:boolean 變量來控制是否展示加載動畫
@Component
export struct BasePage {
@Prop netLoad: boolean
//指向一個組件
@BuilderParam aB0: () = > {}
build(){
Stack(){
//為組件占位
this.aB0()
if (this.netLoad) {
LoadingProgress()
.width(px2vp(150))
.height(px2vp(150))
.color(Color.Blue)
}
}.hitTestBehavior(HitTestMode.None)
}
}
主頁面布局代碼
import { BasePage } from './BasePage'
@Entry
@Component
struct NetIndex {
@State netLoad: number = 0
@State msg: string = ''
build() {
Stack(){
BasePage({netLoad: this.netLoad != 0}) {
Column( {space: 20} ){
Row({space: 20}){
Text('WeiBo').fontColor(Color.Black)
Text('UniDemo').fontColor(Color.Black)
Text('HuaWei').fontColor(Color.Black)
}
Row({space: 20}){
Text('WeiBo' + this.weiboIndex)
Text('UniDemo' + this.uniIndex)
Text('HuaWei' + this.huaweiIndex)
}
Button('開始網絡請求 - 異步').fontSize(20).onClick( () = > {
...
})
Button('開始網絡請求 - 同步').fontSize(20).onClick( () = > {
...
})
Button('開始網絡請求-自定義方法裝飾器').fontSize(20).onClick( () = > {
...
})
Scroll() {
Text(this.msg).width('100%')
}
.scrollable(ScrollDirection.Vertical)
}
.width('100%')
.height('100%')
.padding({top: px2vp(120)})
}
}
}
}
簡單裝封裝網絡請求
函數傳參,直接調用封裝方法
WeiBo為數據結構體,暫時不用關心,后續會貼出完整代碼,這里僅僅是演示網絡請求用法
//引用封裝好的HNet網絡工具類
import HNet from './util/HNet'
@State msg: string = ''
getWeiBoData(){
HNet.get< WeiBo >({
url: 'https://m.weibo.cn/api/feed/trendtop?containerid=102803_ctg1_4188_-_ctg1_4188',
}).then( (r) = > {
this.msg = ''
if(r.code == 0 && r.result){
r.result.data.statuses.forEach((value: WeiBoItem) = > {
this.msg = this.msg.concat(value.created_at + ' ' + value.id + 'n')
})
} else {
this.msg = r.code + ' ' + r.msg
}
console.log('順序-weibo-' + (new Date().getTime() - starTime))
this.netLoad--
})
}
自定義方法裝飾器,完成傳參調用
網絡請求樣例
NetController.getWeiBo< WeiBo >().then( r = > {
......
})
復制
按照業務定義傳參
import { Get, NetResponse } from './util/HNet'
export default class BizNetController {
@Get('https://m.weibo.cn/api/feed/trendtop?containerid=102803_ctg1_4188_-_ctg1_4188')
static getWeiBo< WeiBo >(): Promise< NetResponse< WeiBo >>{ return }
}
復制
封裝的網絡請求代碼
import http from '@ohos.net.http';
//自定義網絡請求參數對象
class NetParams{
url: string
extraData?: JSON
}
//自定義數據公共結構體
export class NetResponse< T > {
result: T
code: number
msg: string
}
//網絡封裝工具類
class HNet {
//POST 請求方法
static post< T >(options: NetParams): Promise< NetResponse< T >>{
return this.request(options, http.RequestMethod.POST)
}
//GET 請求方法
static get< T >(options: NetParams): Promise< NetResponse< T >>{
return this.request(options, http.RequestMethod.GET)
}
private static request< T >(options: NetParams, method: http.RequestMethod): Promise< NetResponse< T >>{
let r = http.createHttp()
return r.request(options.url, {
method: method,
extraData: options.extraData != null ? JSON.stringify(options.extraData) : null
}).then( (response: http.HttpResponse) = > {
let netResponse = new NetResponse< T >()
let dataType = typeof response.result
if(dataType === 'string'){
console.log('結果為字符串類型')
}
if(response.responseCode == 200){
netResponse.code = 0
netResponse.msg = 'success'
netResponse.result = JSON.parse(response.result as string)
} else {
//出錯
netResponse.code = -1
netResponse.msg = 'error'
}
return netResponse
}).catch( reject = > {
console.log('結果發生錯誤')
let netResponse = new NetResponse< T >()
netResponse.code = reject.code
netResponse.msg = reject.message
return netResponse
}).finally( () = > {
//網絡請求完成后,需要進行銷毀
r.destroy()
})
}
}
export default HNet
//用于裝飾器傳參
export function Get(targetUrl: string) : MethodDecorator {
return (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) = > {
//替換方法
descriptor.value = () = > {
let options = new NetParams()
options.url = targetUrl
return HNet.get(options)
}
}
}
完整代碼
代碼結構
net/BasePage.ets
net/NetRequest.ets
net/util/HNet.ts
net/viewmodel/WeiBoModel.ts
net/BizNetController.ets
詳細代碼
@Component
export struct BasePage {
@Prop netLoad: boolean
@BuilderParam aB0: () = > {}
build(){
Stack(){
this.aB0()
if (this.netLoad) {
LoadingProgress()
.width(px2vp(150))
.height(px2vp(150))
.color(Color.Blue)
}
}.hitTestBehavior(HitTestMode.None)
}
}
import HNet from './util/HNet'
import NetController from './BizNetController'
import { WeiBo, WeiBoItem } from './viewmodel/WeiBoModel'
import { BasePage } from './BasePage'
@Entry
@Component
struct NetIndex {
@State netLoad: number = 0
@State msg: string = ''
@State weiboColor: Color = Color.Black
@State uniColor: Color = Color.Black
@State huaweiColor: Color = Color.Black
@State weiboIndex: number = 1
@State uniIndex: number = 2
@State huaweiIndex: number = 3
private TEST_Target_URL: string[] = [
'https://m.weibo.cn/api/feed/trendtop?containerid=102803_ctg1_4188_-_ctg1_4188',
'https://unidemo.dcloud.net.cn/api/news',
'https://developer.huawei.com/config/cn/head.json',
]
build() {
Stack(){
BasePage({netLoad: this.netLoad != 0}) {
Column( {space: 20} ){
Row({space: 20}){
Text('WeiBo').fontColor(Color.Black)
Text('UniDemo').fontColor(Color.Black)
Text('HuaWei').fontColor(Color.Black)
}
Row({space: 20}){
Text('WeiBo' + this.weiboIndex).fontColor(this.weiboColor)
Text('UniDemo' + this.uniIndex).fontColor(this.uniColor)
Text('HuaWei' + this.huaweiIndex).fontColor(this.huaweiColor)
}
Button('開始網絡請求 - 異步').fontSize(20).onClick( () = > {
this.weiboColor = Color.Black
this.uniColor = Color.Black
this.huaweiColor = Color.Black
this.weiboIndex = 1
this.uniIndex = 2
this.huaweiIndex = 3
this.asyncGetData()
})
Button('開始網絡請求 - 同步').fontSize(20).onClick( () = > {
this.weiboColor = Color.Black
this.uniColor = Color.Black
this.huaweiColor = Color.Black
this.weiboIndex = 1
this.uniIndex = 2
this.huaweiIndex = 3
this.syncGetData()
})
Button('開始網絡請求-自定義方法裝飾器').fontSize(20).onClick( () = > {
this.getWeiBoListByController()
})
Scroll() {
Text(this.msg).width('100%')
}
.scrollable(ScrollDirection.Vertical)
}
.width('100%')
.height('100%')
.padding({top: px2vp(120)})
}
}
}
asyncGetData(){
this.netLoad = 3;
this.TEST_Target_URL.forEach( (value) = > {
HNet.get({
url: value,
}).then( (r) = > {
this.msg = JSON.stringify(r)
if(value.indexOf('weibo') != -1){
this.weiboColor = Color.Green
this.weiboIndex = 3 - this.netLoad + 1
} else if(value.indexOf('unidemo') != -1){
this.uniColor = Color.Green
this.uniIndex = 3 - this.netLoad + 1
} else if(value.indexOf('huawei') != -1){
this.huaweiColor = Color.Green
this.huaweiIndex = 3 - this.netLoad + 1
}
this.netLoad--
})
})
}
async syncGetData() {
let starTime
let url
this.netLoad = 3;
starTime = new Date().getTime()
url = this.TEST_Target_URL[0]
starTime = new Date().getTime()
if(url.indexOf('weibo') != -1){
console.log('順序-請求-weibo')
} else if(url.indexOf('unidemo') != -1){
console.log('順序-請求-unidemo')
} else if(url.indexOf('huawei') != -1){
console.log('順序-請求-huawei')
}
await HNet.get< WeiBo >({
url: url,
}).then( (r) = > {
this.msg = ''
if(r.code == 0 && r.result){
r.result.data.statuses.forEach((value: WeiBoItem) = > {
this.msg = this.msg.concat(value.created_at + ' ' + value.id + 'n')
})
} else {
this.msg = r.code + ' ' + r.msg
}
if(url.indexOf('weibo') != -1){
this.weiboColor = Color.Green
this.weiboIndex = 3 - this.netLoad + 1
console.log('順序-返回-weibo-' + (new Date().getTime() - starTime))
} else if(url.indexOf('unidemo') != -1){
this.uniColor = Color.Green
this.uniIndex = 3 - this.netLoad + 1
console.log('順序-返回-unidemo-' + (new Date().getTime() - starTime))
} else if(url.indexOf('huawei') != -1){
this.huaweiColor = Color.Green
this.huaweiIndex = 3 - this.netLoad + 1
console.log('順序-返回-huawei-' + (new Date().getTime() - starTime))
}
this.netLoad--
})
starTime = new Date().getTime()
url = this.TEST_Target_URL[1]
starTime = new Date().getTime()
if(url.indexOf('weibo') != -1){
console.log('順序-請求-weibo')
} else if(url.indexOf('unidemo') != -1){
console.log('順序-請求-unidemo')
} else if(url.indexOf('huawei') != -1){
console.log('順序-請求-huawei')
}
await HNet.get({
url: url,
}).then( (r) = > {
this.msg = JSON.stringify(r)
if(url.indexOf('weibo') != -1){
this.weiboColor = Color.Green
this.weiboIndex = 3 - this.netLoad + 1
console.log('順序-返回-weibo-' + (new Date().getTime() - starTime))
} else if(url.indexOf('unidemo') != -1){
this.uniColor = Color.Green
this.uniIndex = 3 - this.netLoad + 1
console.log('順序-返回-unidemo-' + (new Date().getTime() - starTime))
} else if(url.indexOf('huawei') != -1){
this.huaweiColor = Color.Green
this.huaweiIndex = 3 - this.netLoad + 1
console.log('順序-返回-huawei-' + (new Date().getTime() - starTime))
}
this.netLoad--
})
starTime = new Date().getTime()
url = this.TEST_Target_URL[2]
starTime = new Date().getTime()
if(url.indexOf('weibo') != -1){
console.log('順序-請求-weibo')
} else if(url.indexOf('unidemo') != -1){
console.log('順序-請求-unidemo')
} else if(url.indexOf('huawei') != -1){
console.log('順序-請求-huawei')
}
await HNet.get({
url: url,
}).then( (r) = > {
this.msg = JSON.stringify(r)
if(url.indexOf('weibo') != -1){
this.weiboColor = Color.Green
this.weiboIndex = 3 - this.netLoad + 1
console.log('順序-返回-weibo-' + (new Date().getTime() - starTime))
} else if(url.indexOf('unidemo') != -1){
this.uniColor = Color.Green
this.uniIndex = 3 - this.netLoad + 1
console.log('順序-返回-unidemo-' + (new Date().getTime() - starTime))
} else if(url.indexOf('huawei') != -1){
this.huaweiColor = Color.Green
this.huaweiIndex = 3 - this.netLoad + 1
console.log('順序-返回-huawei-' + (new Date().getTime() - starTime))
}
this.netLoad--
})
}
getHuaWeiSomeDataByNet(){
this.netLoad = 1
let starTime = new Date().getTime()
console.log('順序-huawei-請求' + starTime)
HNet.get({
url: 'https://developer.huawei.com/config/cn/head.json',
}).then( (r) = > {
this.msg = JSON.stringify(r, null, 't')
this.netLoad--
console.log('順序-huawei-' + (new Date().getTime() - starTime))
})
}
getWeiBoListByHNet(){
this.netLoad = 1
let starTime = new Date().getTime()
console.log('順序-weibo-請求' + starTime)
HNet.get< WeiBo >({
url: 'https://m.weibo.cn/api/feed/trendtop?containerid=102803_ctg1_4188_-_ctg1_4188',
}).then( (r) = > {
this.msg = ''
if(r.code == 0 && r.result){
r.result.data.statuses.forEach((value: WeiBoItem) = > {
this.msg = this.msg.concat(value.created_at + ' ' + value.id + 'n')
})
} else {
this.msg = r.code + ' ' + r.msg
}
console.log('順序-weibo-' + (new Date().getTime() - starTime))
this.netLoad--
})
}
getWeiBoListByController(){
this.netLoad = 1
NetController.getWeiBo< WeiBo >().then( r = > {
this.msg = ''
if(r.code == 0 && r.result){
r.result.data.statuses.forEach((value: WeiBoItem) = > {
this.msg = this.msg.concat(value.created_at + ' ' + value.id + 'n' + value.source + 'n')
})
} else {
this.msg = r.code + ' ' + r.msg
}
this.netLoad--
})
}
}
import { Get, NetResponse } from './util/HNet'
export default class BizNetController {
@Get('https://m.weibo.cn/api/feed/trendtop?containerid=102803_ctg1_4188_-_ctg1_4188')
static getWeiBo< WeiBo >(): Promise< NetResponse< WeiBo >>{ return }
}
import http from '@ohos.net.http';
class NetParams{
url: string
extraData?: JSON
}
export class NetResponse< T > {
result: T
code: number
msg: string
}
class HNet {
static post< T >(options: NetParams): Promise< NetResponse< T >>{
return this.request(options, http.RequestMethod.POST)
}
static get< T >(options: NetParams): Promise< NetResponse< T >>{
return this.request(options, http.RequestMethod.GET)
}
private static request< T >(options: NetParams, method: http.RequestMethod): Promise< NetResponse< T >>{
let r = http.createHttp()
return r.request(options.url, {
method: method,
extraData: options.extraData != null ? JSON.stringify(options.extraData) : null
}).then( (response: http.HttpResponse) = > {
let netResponse = new NetResponse< T >()
let dataType = typeof response.result
if(dataType === 'string'){
console.log('結果為字符串類型')
}
if(response.responseCode == 200){
netResponse.code = 0
netResponse.msg = 'success'
netResponse.result = JSON.parse(response.result as string)
} else {
//出錯
netResponse.code = -1
netResponse.msg = 'error'
}
return netResponse
}).catch( reject = > {
console.log('結果發生錯誤')
let netResponse = new NetResponse< T >()
netResponse.code = reject.code
netResponse.msg = reject.message
return netResponse
}).finally( () = > {
r.destroy()
})
}
}
export default HNet
export function Get(targetUrl: string) : MethodDecorator {
return (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) = > {
//替換方法
descriptor.value = () = > {
let options = new NetParams()
options.url = targetUrl
return HNet.get(options)
}
}
}
export class WeiBo{
ok: number
http_code: number
data: WeiBoDataObj
}
export class WeiBoDataObj{
total_number: number
interval: number
remind_text: string
page: number
statuses: Array< WeiBoItem >
}
export class WeiBoItem{
created_at: string
id: string
source: string
textLength: number
}
-
移動開發
+關注
關注
0文章
52瀏覽量
9836 -
鴻蒙
+關注
關注
57文章
2392瀏覽量
43050 -
HarmonyOS
+關注
關注
79文章
1982瀏覽量
30574 -
OpenHarmony
+關注
關注
25文章
3744瀏覽量
16577 -
鴻蒙OS
+關注
關注
0文章
190瀏覽量
4537
發布評論請先 登錄
相關推薦
評論