官方的 ArkTs 已經(jīng)提供了 @ohos.net.http (數(shù)據(jù)請求) 庫趟咆,并且支持常見的GET、POST梅屉、OPTIONS值纱、HEAD、PUT坯汤、DELETE计雌、TRACE、CONNECT方法玫霎,大多數(shù) App 或者元服務(wù)都能滿足
本文也是對官方網(wǎng)絡(luò)請求庫,進(jìn)行二次封裝妈橄,滿足自己一些特定場景的需要
一庶近、創(chuàng)建 NetWorkManage 實(shí)例
這里主要提供 2 個能力:
- 設(shè)置 BaseUrl,當(dāng)然也支持 path 參數(shù)傳 "http:host/path" 完整的鏈路請求眷蚓,兼容多域名應(yīng)用
- 配置默認(rèn)的 Content-type鼻种、connectTimeout、readTimeout
class NetWorkManage {
private BASE_URL: string = ''
private requestOption: RequestOption = { method: http.RequestMethod.GET, path: '' }
setBaseUrl(url: string) {
this.BASE_URL = url
}
createRequest(requestOption: RequestOption): NetWorkManage {
if (!this.BASE_URL) {
throw Error('BaseUrl not null')
}
let requestConfig = requestOption
let headers: Record<string, string> = requestOption.header || {}
if (!headers['Content-type']) {
headers['Content-type'] = ContentType.JSON
}
requestConfig.header = headers
this.requestOption = requestConfig
return this
}
}
二沙热、添加攔截器
主要涉及到一些對公共 header 處理叉钥,如傳遞用戶 Token等,或者對 data 進(jìn)行二次封裝篙贸,具體依自身業(yè)務(wù)需要來
DefaultHeadersInterceptor 為默認(rèn)的攔截器示例投队,開發(fā)者可以自行修改其中內(nèi)容
InterceptUtil.ets 攔截器類
// 攔截器接口
export interface HttpInterceptor {
intercept: (options: http.HttpRequestOptions) => http.HttpRequestOptions
}
// 默認(rèn)攔截器,可自行修改爵川,下面提供了對請求heade修改的示例
export class DefaultHeadersInterceptor implements HttpInterceptor {
intercept(options: http.HttpRequestOptions) {
let headers: Record<string, string> = options.header as Record<string, string>
headers.test1 = 'test'
return options
}
}
NetWorkManage.ets 請求工具類
// 聲明攔截器數(shù)組
private REQUEST_INTERCEPTORS: Array<HttpInterceptor> = [new DefaultHeadersInterceptor()]
// 添加攔截器
addRequestInterceptor(interceptor: HttpInterceptor) {
this.REQUEST_INTERCEPTORS.push(interceptor)
}
三敷鸦、響應(yīng)攔截器
可以模仿請求攔截器,再單獨(dú)實(shí)現(xiàn)一套響應(yīng)攔截器寝贡,對統(tǒng)一的請求數(shù)據(jù)進(jìn)行處理扒披,但是我們業(yè)務(wù)不太需要,可以自行實(shí)現(xiàn)
InterceptUtil.ets 攔截器類
// 攔截器接口
export interface HttpResponseInterceptor {
intercept: (data: http.HttpResponse) => http.HttpResponse
}
export class DefaultResponseInterceptor implements HttpResponseInterceptor {
intercept(data: http.HttpResponse){
// 對 data 進(jìn)行錯誤類型統(tǒng)一處理
return data
}
}
NetWorkManage.ets 請求工具類
// 聲明響應(yīng)攔截器數(shù)組
private RESPONSE_INTERCEPTORS: Array<HttpInterceptor> = [new DefaultHeadersInterceptor()]
// 添加攔截器
addResponseInterceptor(interceptor: HttpInterceptor) {
this.RESPONSE_INTERCEPTORS.push(interceptor)
}
四圃泡、使用泛型對數(shù)據(jù)轉(zhuǎn)換
- 封裝請求響應(yīng)類 ResponseResult
- 傳入 T 泛型碟案,數(shù)據(jù)轉(zhuǎn)換對應(yīng)類型,返回前臺
ResponseResult.ets 請求響應(yīng)封裝
export default class ResponseResult<T> {
code: string
msg: string | Resource
data?: T
constructor() {
this.code = ''
this.msg = ''
}
}
NetWorkManage.ets 請求工具類
request<T>() {
// http.HttpRequestOptions 處理
...
// http request url
let url = this.requestOption.path
if (!startsWithHttpOrHttps(this.requestOption.path)) {
url = this.BASE_URL + url
}
// execute interceptor
this.REQUEST_INTERCEPTORS.forEach((interceptor: HttpInterceptor) => {
interceptor.intercept(requestOption)
})
let httpRequest = http.createHttp();
// return result
let serverData: ResponseResult<T> = new ResponseResult()
return new Promise<ResponseResult<T>>((resolve, reject) => {
httpRequest.request(url, requestOption).then((value: http.HttpResponse) => {
// 轉(zhuǎn)換數(shù)據(jù)颇蜡,示例是json數(shù)據(jù)价说,如果是xml等需要自行處理
let result: ResponseResult<T> = JSON.parse(`${value.result}`) as ResponseResult<T>
if (value.responseCode === http.ResponseCode.OK && result.code == 'success') {
serverData = result
resolve(serverData)
} else {
serverData.msg = `${$r('app.string.http_error_message')}&${value.responseCode}`
reject(serverData)
}
})
.catch(() => {
serverData.msg = $r('app.string.http_error_message')
reject(serverData)
})
})
}
五辆亏、接口請求示例
在請求過程中,除了攔截器統(tǒng)一處理請求內(nèi)容熔任,也支持單個接口對 header 信息進(jìn)行定制處理
注意:請求 data 可以傳入 string褒链,也可以傳入 object,如果是 get 請求疑苔,官方庫會默認(rèn)轉(zhuǎn)把 object 類型換成 "key1=sss&uuu=222"甫匹,post 請求需要傳入 object
class NewsViewModel {
// 獲取新聞類型
async getNewsTypeList(): Promise<NewsTypeModel[]> {
const result = await NetWorkManage.createRequest({
method: http.RequestMethod.GET,
path: Const.GET_NEWS_TYPE,
header: {
'test222': 'aqqq'
}
}).request<NewsTypeModel[]>()
if (result.code === 'success' && result.data) {
return result.data
}
return Const.TabBars_DEFAULT_NEWS_TYPES;
}
getDefaultNewsType(): NewsTypeModel[] {
return Const.TabBars_DEFAULT_NEWS_TYPES
}
// 獲取新聞列表
getNewsList(currPage: number, pageSize: number, path: string): Promise<ResponseResult<NewsData[]>> {
const params: Record<string, number> = {
'currentPage': currPage,
'pageSize': pageSize
}
return NetWorkManage.createRequest({
method: http.RequestMethod.GET,
path: path,
data: params
}).request<NewsData[]>()
}
}
let newsViewModel = new NewsViewModel();
export default newsViewModel as NewsViewModel;
服務(wù)端代碼
給一個服務(wù)端的簡易代碼,幫助開發(fā)者自行調(diào)試業(yè)務(wù)場景惦费,Python語言
https://gitee.com/Osbornjie/learn-align
pip install flask
pip install faker
python main.py // 啟動服務(wù)
總結(jié)
上面的文章主要介紹了對 htpp 官方庫的封裝兵迅,不需要引入第三方請求庫,基本能滿足大多數(shù)應(yīng)用的開發(fā)薪贫,當(dāng)然也有設(shè)計不足的地方恍箭,比如 請求重試、請求隊(duì)列等瞧省,有時間再優(yōu)化