文章目錄
- 基本使用
- 封裝
- 參考
基本使用
鴻蒙應用發起HTTP請求的基本使用,如下:
- 導入http模塊
- 創建httpRequest對象
- 發起http請求,并處理響應結果
第一、導入http模塊:
import http from '@ohos.net.http'
第二、創建httpRequest對象,注意的是每一個httpRequest對象對應一個http請求任務,不可復用。
const httpRequest = http.createHttp()
第三、發起請求,比如POST
請求
httpRequest.request(// 請求url地址url,{// 請求方式method: http.RequestMethod.POST,// 請求的額外數據。extraData: {"param1": "value1","param2": "value2",},// 可選,默認為60sconnectTimeout: 60000,// 可選,默認為60sreadTimeout: 60000,// 開發者根據自身業務需要添加header字段header: {'Content-Type': 'application/json'}}).then((data) => { if (data.responseCode === http.ResponseCode.OK) {// 處理響應結果// data.result為服務器返回的業務數據console.info('Result:' + data.result);console.info('code:' + data.responseCode);}
}).catch((err) => {console.info('error:' + JSON.stringify(err));
});
最后需要聲明網絡權限,在module.josn5文件中聲明:
{"module" : {"requestPermissions":[{"name": "ohos.permission.INTERNET"}]}
}
上面就是網絡請求的簡單使用,接下來通過Promise
來封裝一個網絡請求庫,統一管理請求參數、響應數據、日志的輸出等,對外屏蔽了細節,使用者只需定義業務數據的實體類以及調用即可。
封裝
以**玩Android**開放接口為測試用例
定義業務數據的實體類,通過泛型來接收不同的數據類型:
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模塊中已經有對應的枚舉,之所以再用一個新枚舉來聲明,是簡化使用,同時也是將http模塊相關細節屏蔽掉不對外開放,這樣可以靈活替換網絡庫。
定義一個HttpUtils
類實現:
const TAG = "HttpUtils"
const BASE_URL = "https://www.wanandroid.com"
export class HttpUtils{public static readonly SUCCESS_CODE: number = 0public static readonly READ_TIME_OUT = 60 * 1000public static readonly CONNECT_TIME_OUT = 60 * 1000private 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}}}request<T>(path: string, reqMethod: RequestMethod, parameter: Map<string, Object> = null): Promise<T | null> {// 注意的是每一個httpRequest對象對應一個http請求任務,不可復用。const httpRequest = http.createHttp()const method = this.methodName(reqMethod)let extraData = {}let url = `${this.baseUrl}/${path}`if (parameter != null) {switch (reqMethod) {case RequestMethod.POST: {extraData = Object.fromEntries(parameter)break;}case RequestMethod.GET: {const urlParams = Object.keys(parameter).map(key => `${key}=${parameter[key]}`).join('&')if (url.includes("?")) {url = `${url}${urlParams}`} else {url = `${url}?${urlParams}`}break;}}}LogUtils.debug(TAG, "==================Request====================")LogUtils.debug(TAG, "url: " + url)LogUtils.debug(TAG, "method: " + method.toString())if (reqMethod == RequestMethod.POST)LogUtils.debug(TAG, "extraData: " + JSON.stringify(parameter, null, 2))return new Promise((resolve, reject) => {httpRequest.request(url,{method,readTimeout: HttpUtils.READ_TIME_OUT,connectTimeout: HttpUtils.CONNECT_TIME_OUT,header: {'Content-Type': 'application/json'},extraData}).then((value) => {LogUtils.debug(TAG, "==================Response====================")LogUtils.debug(TAG, "url: " + url)LogUtils.debug(TAG, "method: " + method.toString())LogUtils.debug(TAG, "header: " + JSON.stringify(value.header, null, 2))LogUtils.debug(TAG, "responseCode: " + value.responseCode)LogUtils.debug(TAG, "resultType: " + value.resultType)if (value.responseCode == http.ResponseCode.OK) {let result: ResponseResult<T> = JSON.parse(value.result.toString())LogUtils.debug(TAG, "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
使用發起網絡請求:
aboutToAppear() {let map = new Map<string,string>()map["cid"] = 294YiNet.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})})}
日志輸出:
參考
- https://developer.huawei.com/consumer/cn/training/course/slightMooc/C101667364948559963?ha_linker=eyJ0cyI6MTcwMjE3NzI3OTYyMywiaWQiOiI4MmM3ZTI1MmFmMDJlMDZiODBmOGU1ZDM5ZTI5YmMyOCJ9
- https://www.wanandroid.com/blog/show/2