前言
現(xiàn)在網(wǎng)上的應(yīng)用,基本都是網(wǎng)絡(luò)應(yīng)用,需要進(jìn)行聯(lián)網(wǎng)獲取數(shù)據(jù),而常用的聯(lián)網(wǎng)獲取數(shù)據(jù)的方式有http、socket、websocket等。
在鴻蒙應(yīng)用、服務(wù)中,stage模式開發(fā)下,鴻蒙官方為我們提供了一個(gè)網(wǎng)絡(luò)組件庫(kù) http ,我們通過(guò)
import http from ‘@ohos.net.http’; 即可以完成引用。
http網(wǎng)絡(luò)庫(kù)組件介紹
@ohos.net.http (數(shù)據(jù)請(qǐng)求)
該組件提供HTTP數(shù)據(jù)請(qǐng)求能力。應(yīng)用可以通過(guò)HTTP發(fā)起一個(gè)數(shù)據(jù)請(qǐng)求,支持常見的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。
具體查看官網(wǎng)
通過(guò)官網(wǎng)的介紹,可以很快上手該組件的使用,下面我們對(duì)該網(wǎng)絡(luò)庫(kù)進(jìn)行簡(jiǎn)單的封裝,方便我們的使用
http網(wǎng)絡(luò)庫(kù)封裝
網(wǎng)絡(luò)庫(kù)工程結(jié)構(gòu)如下圖:
具體步驟如下:
- 創(chuàng)建Har Module
- 創(chuàng)建RequestOption請(qǐng)求配置類
- 創(chuàng)建HttpCore核心類
- 創(chuàng)建HttpManager對(duì)外管理類
- 對(duì)外組件導(dǎo)出
- 添加網(wǎng)絡(luò)權(quán)限
創(chuàng)建Har Module
我們創(chuàng)建一個(gè)Module ,類型選擇為Har,3.1Beta IDE選擇 Visual Library,這里我們創(chuàng)建module名稱為
httpLibrary。
創(chuàng)建RequestOption 配置類
代碼如下:
/**
* <pre>
* @desc : 網(wǎng)絡(luò)請(qǐng)求配置
* </pre>
*/
export interface RequestOptions {
/**
* Request url.
*/
url?: string;
/**
* Request method.
*/
method?: RequestMethod; // default is GET
/**
* Request url queryParams .
*/
queryParams ?: Record<string, string>;
/**
* Additional data of the request.
* extraData can be a string or an Object (API 6) or an ArrayBuffer(API 8).
*/
extraData?: string | Object | ArrayBuffer;
/**
* HTTP request header.
*/
header?: Object; // default is 'content-type': 'application/json'
}
export enum RequestMethod {
OPTIONS = "OPTIONS",
GET = "GET",
HEAD = "HEAD",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
TRACE = "TRACE",
CONNECT = "CONNECT"
}
這里字段大家可自行拓展,我這里簡(jiǎn)單添加了幾個(gè)常用字段,包括url、urlParams、header、extraData、大家也可以增加一些諸如UserAgent之類的網(wǎng)絡(luò)配置。
創(chuàng)建HttpCore核心類
該類使我們這個(gè)網(wǎng)絡(luò)庫(kù)的主要核心代碼實(shí)現(xiàn),主要封裝’@ohos.net.http的API調(diào)用,提供便捷使用的API。
import http from '@ohos.net.http';
import { RequestOptions } from './RequestOptions';
/**
* Http請(qǐng)求器
*/
export class HttpCore {
/**
* 發(fā)送請(qǐng)求
* @param requestOption
* @returns Promise
*/
request<T>(requestOption: RequestOptions): Promise<T> {
return new Promise<T>((resolve, reject) => {
this.sendRequest(requestOption)
.then((response) => {
if (typeof response.result !== 'string') {
reject(new Error('Invalid data type'));
} else {
let bean: T = JSON.parse(response.result);
if (bean) {
resolve(bean);
} else {
reject(new Error('Invalid data type,JSON to T failed'));
}
}
})
.catch((error) => {
reject(error);
});
});
}
private sendRequest(requestOption: RequestOptions): Promise<http.HttpResponse> {
// 每一個(gè)httpRequest對(duì)應(yīng)一個(gè)HTTP請(qǐng)求任務(wù),不可復(fù)用
let httpRequest = http.createHttp();
let resolveFunction, rejectFunction;
const resultPromise = new Promise<http.HttpResponse>((resolve, reject) => {
resolveFunction = resolve;
rejectFunction = reject;
});
if (!this.isValidUrl(requestOption.url)) {
return Promise.reject(new Error('url格式不合法.'));
}
let promise = httpRequest.request(this.appendQueryParams(requestOption.url, requestOption.queryParams), {
method: requestOption.method,
header: requestOption.header,
extraData: requestOption.extraData, // 當(dāng)使用POST請(qǐng)求時(shí)此字段用于傳遞內(nèi)容
expectDataType: http.HttpDataType.STRING // 可選,指定返回?cái)?shù)據(jù)的類型
});
promise.then((response) => {
console.info('Result:' + response.result);
console.info('code:' + response.responseCode);
console.info('header:' + JSON.stringify(response.header));
if (http.ResponseCode.OK !== response.responseCode) {
throw new Error('http responseCode !=200');
}
resolveFunction(response);
}).catch((err) => {
rejectFunction(err);
}).finally(() => {
// 當(dāng)該請(qǐng)求使用完畢時(shí),調(diào)用destroy方法主動(dòng)銷毀。
httpRequest.destroy();
})
return resultPromise;
}
private appendQueryParams(url: string, queryParams: Record<string, string>): string {
// todo 使用將參數(shù)拼接到url上
return url;
}
private isValidUrl(url: string): boolean {
//todo 實(shí)現(xiàn)URL格式判斷
return true;
}
}
export const httpCore = new HttpCore();
代碼講解:
- expectDataType: http.HttpDataType.STRING,這里固定了返回?cái)?shù)據(jù)為string,大家也可以通過(guò)RequestOptions中定義字段傳入,這里定義為string只是方便后續(xù)的string轉(zhuǎn)Bean;
- 定義sendRequest方法。
- 對(duì)請(qǐng)求配置進(jìn)行處理,這里進(jìn)行對(duì)Url進(jìn)行格式判斷,如果非正確格式,需要對(duì)外拋出錯(cuò)誤;需要進(jìn)行Url參數(shù)拼接;可對(duì)請(qǐng)求參數(shù)、請(qǐng)求結(jié)果進(jìn)行日志打??;對(duì)Http響應(yīng)碼進(jìn)行判斷,按200和非200請(qǐng)求碼進(jìn)行分類返回。
- 定義 request 進(jìn)行請(qǐng)求結(jié)果轉(zhuǎn)Bean的處理(這里默認(rèn)返回?cái)?shù)據(jù)為JSON 字符串,其他類型自行拓展),該方法也是對(duì)外的唯一函數(shù)。
創(chuàng)建HttpManager核心類
import { RequestOptions } from './RequestOptions';
import { httpCore as HttpCore } from './HttpCore';
/**
* <pre>
* @desc : 對(duì)外管理器
* </pre>
*/
export class HttpManager {
private static mInstance: HttpManager;
// 防止實(shí)例化
private constructor() {
}
static getInstance(): HttpManager {
if (!HttpManager.mInstance) {
HttpManager.mInstance = new HttpManager();
}
return HttpManager.mInstance;
}
request<T>(option: RequestOptions): Promise<T> {
return HttpCore.request(option);
}
}
HttpManager 為對(duì)外API調(diào)用入口類,提供單例對(duì)象跟發(fā)送請(qǐng)求API。
對(duì)外組件導(dǎo)出
在httpLibrary模塊的根目錄下有一個(gè) index.ets文件,在該文件中進(jìn)行需要對(duì)外導(dǎo)出的組件定義
export { HttpManager } from './src/main/ets/http/HttpManager';
export { RequestMethod } from './src/main/ets/http/RequestOptions';
到這里我們就完成了一個(gè)簡(jiǎn)易的網(wǎng)絡(luò)庫(kù)封裝,我們可以將該module導(dǎo)出Har包對(duì)外提供,也可以直接在項(xiàng)目中使用該module。
添加網(wǎng)絡(luò)權(quán)限
漏了一點(diǎn),這里記得為該網(wǎng)絡(luò)庫(kù)添加上網(wǎng)絡(luò)權(quán)限哦,在module.json5文件中
"requestPermissions": [
{
"name": 'ohos.permission.INTERNET'
}
]
http網(wǎng)絡(luò)庫(kù)依賴和使用
依賴http網(wǎng)絡(luò)庫(kù)(httpLibrary)
打開entry下的 oh-package.json5文件,增加如下依賴:
"dependencies": {
'@ohos/http_library': 'file:../httpLibrary'
}
使用http網(wǎng)絡(luò)庫(kù)(httpLibrary)
這里我們寫一個(gè)例子,使用該網(wǎng)絡(luò)庫(kù)進(jìn)行發(fā)送一個(gè)get請(qǐng)求
在entry下,任意頁(yè)面中,進(jìn)行請(qǐng)求調(diào)用。
handleClick() {
HttpManager.getInstance()
.request<TestBean>({
method: RequestMethod.GET,
url: 'https://jsonplaceholder.typicode.com/todos/1' //公開的API
})
.then((result) => {
console.info(JSON.stringify(result));
})
.catch((err) => {
console.error(JSON.stringify(err));
});
}
https://jsonplaceholder.typicode.com/todos/1 是一個(gè)公開的get請(qǐng)求API(如果侵權(quán),請(qǐng)聯(lián)系我刪除,謝謝?。?br> 這里我們定一個(gè)了一個(gè)TestBean,進(jìn)行數(shù)據(jù)解析
/**
* <pre>
* @desc : 測(cè)試Bean
* </pre>
*/
export interface TestBean {
/**
* {
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
*/
userId: number,
id: number,
title: string,
completed: boolean
}
這樣就完成了調(diào)用,接著我們將應(yīng)用裝機(jī),點(diǎn)擊獲取數(shù)據(jù)按鈕,可以在log面板看到如下輸出:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-612312.html
文章到此結(jié)束,需要Demo的或者是有問(wèn)題交流的,歡迎評(píng)論區(qū)留言。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-612312.html
到了這里,關(guān)于【鴻蒙應(yīng)用ArkTS開發(fā)系列】- http網(wǎng)絡(luò)庫(kù)使用講解和封裝的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!