網(wǎng)絡(luò)基礎(chǔ)
- 網(wǎng)絡(luò)基礎(chǔ)-TCPIP協(xié)議分層模型
- TCP協(xié)議-三次握手與四次揮手
- UDP協(xié)議-簡單高效的傳輸協(xié)議
- HTTP協(xié)議-應(yīng)用間的通信協(xié)議
基本使用
鴻蒙應(yīng)用發(fā)起HTTP請求的基本使用,如下:
- 導(dǎo)入http模塊
- 創(chuàng)建httpRequest對象
- 發(fā)起http請求,并處理響應(yīng)結(jié)果
第一、導(dǎo)入http模塊:
import http from '@ohos.net.http'
第二、創(chuàng)建httpRequest對象,注意的是每一個httpRequest對象對應(yīng)一個http請求任務(wù),不可復(fù)用。
const httpRequest = http.createHttp()
第三、發(fā)起請求,比如POST
請求
httpRequest.request(
// 請求url地址
url,
{
// 請求方式
method: http.RequestMethod.POST,
// 請求的額外數(shù)據(jù)。
extraData: {
"param1": "value1",
"param2": "value2",
},
// 可選,默認(rèn)為60s
connectTimeout: 60000,
// 可選,默認(rèn)為60s
readTimeout: 60000,
// 開發(fā)者根據(jù)自身業(yè)務(wù)需要添加header字段
header: {
'Content-Type': 'application/json'
}
})
.then((data) => {
if (data.responseCode === http.ResponseCode.OK) {
// 處理響應(yīng)結(jié)果
// data.result為服務(wù)器返回的業(yè)務(wù)數(shù)據(jù)
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
}
}).catch((err) => {
console.info('error:' + JSON.stringify(err));
});
最后需要聲明網(wǎng)絡(luò)權(quán)限,在module.josn5文件中聲明:
{
"module" : {
"requestPermissions":[
{
"name": "ohos.permission.INTERNET"
}
]
}
}
上面就是網(wǎng)絡(luò)請求的簡單使用,接下來通過Promise
來封裝一個網(wǎng)絡(luò)請求庫,統(tǒng)一管理請求參數(shù)、響應(yīng)數(shù)據(jù)、日志的輸出等,對外屏蔽了細(xì)節(jié),使用者只需定義業(yè)務(wù)數(shù)據(jù)的實體類以及調(diào)用即可。
封裝
以**玩Android**開放接口為測試用例
定義業(yè)務(wù)數(shù)據(jù)的實體類,通過泛型來接收不同的數(shù)據(jù)類型:
export class ResponseResult<T> {
errorCode: number;
errorMsg: string;
data?: T | Object | string;
}
把各種請求方式用枚舉聲明RequestMethod
export enum RequestMethod {
OPTIONS,
GET,
HEAD,
POST ,
PUT,
DELETE,
TRACE,
CONNECT
}
其實在http模塊中已經(jīng)有對應(yīng)的枚舉,之所以再用一個新枚舉來聲明,是簡化使用,同時也是將http模塊相關(guān)細(xì)節(jié)屏蔽掉不對外開放,這樣就可以靈活替換網(wǎng)絡(luò)庫,也具有擴(kuò)展性。
定義一個HttpUtils
類實現(xiàn):
export class HttpUtils{
public static readonly SUCCESS_CODE: number = 0
public static readonly READ_TIME_OUT = 60 * 1000
public static readonly CONNECT_TIME_OUT = 60 * 1000
private baseUrl: string = ""
constructor(baseUrl: string) {
this.baseUrl = baseUrl
}
private methodName(method: RequestMethod): http.RequestMethod {
switch (method){
case RequestMethod.OPTIONS:{
return http.RequestMethod.OPTIONS
}
case RequestMethod.GET:{
return http.RequestMethod.GET
}
case RequestMethod.HEAD:{
return http.RequestMethod.HEAD
}
case RequestMethod.POST:{
return http.RequestMethod.POST
}
case RequestMethod.PUT:{
return http.RequestMethod.PUT
}
case RequestMethod.DELETE:{
return http.RequestMethod.DELETE
}
case RequestMethod.TRACE:{
return http.RequestMethod.TRACE
}
case RequestMethod.CONNECT:{
return http.RequestMethod.CONNECT
}
}
}
private tag(n: string): string {
return `${TAG}/${n}`
}
request<T>(path: string, reqMethod: RequestMethod, parameter: Map<string, Object> = null): Promise<T | null> {
// 注意的是每一個httpRequest對象對應(yīng)一個http請求任務(wù),不可復(fù)用。
const httpRequest = http.createHttp()
const method = this.methodName(reqMethod)
let extraData = {}
let url = `${this.baseUrl}/${path}`
if (parameter != null) {
switch (reqMethod) {
case RequestMethod.POST, RequestMethod.PUT: {
extraData = Object.fromEntries(parameter)
break;
}
case RequestMethod.GET,RequestMethod.DELETE: {
const urlParams = Object.keys(parameter).map(key => `${key}=${parameter[key]}`).join('&')
if (url.includes("?")) {
url = `${url}${urlParams}`
} else {
url = `${url}?${urlParams}`
}
break;
}
}
}
let n = Math.random().toString(10).slice(2)
LogUtils.debug(this.tag(n), "==================Request====================")
LogUtils.debug(this.tag(n), "url: " + url)
LogUtils.debug(this.tag(n), "method: " + method.toString())
if (reqMethod == RequestMethod.POST || reqMethod == RequestMethod.PUT)
LogUtils.debug(this.tag(n), "extraData: " + JSON.stringify(parameter, null, 2))
return new Promise( async (resolve, reject) => {
let beginTime = await systemDateTime.getCurrentTime(false)
httpRequest.request(url,
{
method,
readTimeout: HttpUtils.READ_TIME_OUT,
connectTimeout: HttpUtils.CONNECT_TIME_OUT,
header: {
'Content-Type': 'application/json'
},
extraData
}
).then( async (value) => {
let endTime = await systemDateTime.getCurrentTime(false)
LogUtils.debug(this.tag(n), "==================Response====================")
LogUtils.debug(this.tag(n), "url: " + url + " "+ (endTime - beginTime)+"ms")
LogUtils.debug(this.tag(n), "method: " + method.toString())
LogUtils.debug(this.tag(n), "header: " + JSON.stringify(value.header, null, 2))
LogUtils.debug(this.tag(n), "responseCode: " + value.responseCode)
LogUtils.debug(this.tag(n), "resultType: " + value.resultType)
if (value.responseCode == http.ResponseCode.OK) {
let result: ResponseResult<T> = JSON.parse(value.result.toString())
LogUtils.debug(this.tag(n), "body: " + JSON.stringify(result, null, 2))
if (result.errorCode == HttpUtils.SUCCESS_CODE) {
resolve(result.data as T)
} else {
reject(result.errorMsg)
}
} else {
reject("請求失敗")
}
}).catch((reason) => {
reject(reason)
})
})
}
get<T>(path: string, parameter: Map<string, Object> = null): Promise<T | null> {
return this.request<T>(path, RequestMethod.GET, parameter)
}
post<T>(path: string, parameter: Map<string, Object> = null): Promise<T | null> {
return this.request<T>(path, RequestMethod.POST, parameter)
}
delete<T>(path: string, parameter: Map<string, Object> = null): Promise<T | null> {
return this.request<T>(path, RequestMethod.DELETE, parameter)
}
put<T>(path: string, parameter: Map<string, Object> = null): Promise<T | null> {
return this.request<T>(path, RequestMethod.PUT, parameter)
}
}
const YiNet = new HttpUtils(BASE_URL)
export default YiNet
使用發(fā)起網(wǎng)絡(luò)請求:
aboutToAppear() {
let map = new Map<string,string>()
map["cid"] = 294
YiNet.get<ArticleList>("project/list/1/json",map).then((data)=>{
this.data = JSON.stringify(data, null, 2)
})
let map2 = new Map<string,string>()
map2["username"] = "123"
map2["password"] = "123456"
YiNet.post<User>("user/login",map2).then((data)=>{
this.data = JSON.stringify(data, null, 2)
}).catch((err)=>{
Prompt.showToast({message:err})
})
}
日志輸出效果:
如果有多個請求,日志可能會混合交叉不利于查看,可以通過HttpUtils/xxxxxx
來查看具體某一個請求日志,其中xxxx
是一個隨機(jī)數(shù)大部分情況下是具有唯一性。文章來源:http://www.zghlxwxcb.cn/news/detail-764461.html
上面就是官方的http模塊的基本封裝,在此基礎(chǔ)上可以設(shè)計一套攔截器來輔助業(yè)務(wù)需求。文章來源地址http://www.zghlxwxcb.cn/news/detail-764461.html
參考
- https://developer.huawei.com/consumer/cn/training/course/slightMooc/C101667364948559963?ha_linker=eyJ0cyI6MTcwMjE3NzI3OTYyMywiaWQiOiI4MmM3ZTI1MmFmMDJlMDZiODBmOGU1ZDM5ZTI5YmMyOCJ9
- https://www.wanandroid.com/blog/show/2
到了這里,關(guān)于HarmonyOS鴻蒙應(yīng)用開發(fā)——HTTP網(wǎng)絡(luò)訪問與封裝的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!