赞
踩
DevEco Studio版本:4.0.0.600
参考文档:OpenHarmony http数据请求
File-->New-->Module,选择Static Library
HttpCore:Http的核心类,用于http的请求
RequestMethod:http请求的类型,包含:GET、POST等
RequestOptions:http的请求配置,包含:请求的url、请求头等
HttpManager:Http请求的管理类
然后在HttpLibrary的Index.ets类中添加对外输出的引用
- export { HttpManager } from './src/main/ets/HttpManager'
-
- export { RequestMethod } from './src/main/ets/http/RequestMethod'
- import http from '@ohos.net.http';
- import { RequestOptions } from './RequestOptions';
-
- /**
- * Http请求器
- */
- export class HttpCore {
- /**
- * 发送请求
- */
- 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> {
-
- // 每一个httpRequest对应一个HTTP请求任务,不可复用
- 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(requestOption.url, {
- method: requestOption.method,
- header: requestOption.header,
- extraData: requestOption.extraData, // 当使用POST请求时此字段用于传递内容
- expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
- readTimeout: requestOption.readTimeout ? requestOption.readTimeout : 60000,
- connectTimeout: requestOption.connectTimeout ? requestOption.connectTimeout : 60000
- });
-
- 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(() => {
- // 当该请求使用完毕时,调用destroy方法主动销毁。
- httpRequest.destroy();
- })
- return resultPromise;
- }
-
- /**
- * 判断Url格式是否合法
- */
- private isValidUrl(url: string): boolean {
- return url.startsWith("http://") || url.startsWith("https://");
-
- }
- }
-
- export const httpCore = new HttpCore();
-
- export enum RequestMethod {
- OPTIONS = "OPTIONS",
- GET = "GET",
- HEAD = "HEAD",
- POST = "POST",
- PUT = "PUT",
- DELETE = "DELETE",
- TRACE = "TRACE",
- CONNECT = "CONNECT"
- }
- import { RequestMethod } from './RequestMethod';
-
- /**
- *
- * 网络请求配置
- */
- export interface RequestOptions {
-
- /**
- * 请求的url.
- */
- url?: string;
-
- /**
- * 请求的方法,默认GET.
- */
- method?: RequestMethod;
-
- /**
- * 请求的其他数据
- * extraData can be a string or an Object (API 6) or an ArrayBuffer(API 8).
- */
- extraData?: string | Object | ArrayBuffer;
-
- /**
- * HTTP 请求头,默认值:'content-type': 'application/json'
- */
- header?: Object;
-
- /**
- *读取超时时间 单位毫秒 默认60000ms
- */
- readTimeout?: number;
-
- /**
- *连接超时时间 单位毫秒 默认60000ms
- */
- connectTimeout?: number;
- }
- import { RequestOptions } from './http/RequestOptions';
- import { httpCore as HttpCore } from './http//HttpCore';
-
- /**
- * Http对外管理器
- */
- export class HttpManager {
- private static mInstance: HttpManager;
-
- // 防止实例化
- 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);
- }
- }
-
参考链接:静态har共享包
在Entry目录下的oh-package.json5文件中添加对HttpLibaray的引用,鼠标放在错误提示上出现Run "ohpm install",并执行以下。
- "dependencies": {
- "@app/HttpLibrary": "file:../HttpLibrary"
- }
执行完成后会在entry目录下的oh_moudles目录下出现HttpLibrary就说明引用成功了
- import { HttpManager, RequestMethod } from "@app/HttpLibrary"
- import { HotKeyBean, DataBean } from '../bean/HotKeyBean';
-
- @Entry
- @Component
- struct Index {
- @State message: string = '';
-
- build() {
- Row() {
- Column() {
- Text(this.message)
- .fontSize(15)
- .fontWeight(FontWeight.Bold)
-
- Button("获取数据")
- .fontSize(30)
- .padding(15)
- .onClick(() => {
- this.getData()
- })
- }
- .width('100%')
- }
- .height('100%')
- }
-
- private getData(): void {
- HttpManager.getInstance()
- .request<HotKeyBean>({
- method: RequestMethod.GET,
- url: 'https://www.wanandroid.com/hotkey/json' //wanandroid的API
- })
- .then((result: HotKeyBean) => {
- console.info("22222222222222222 result: " + JSON.stringify(result))
- if (result.errorCode == 0) {
- var data: DataBean[] = result.data
- for (let i = 0; i < data.length; i++) {
- this.message = this.message + data[i].name + "\n"
- }
- }
- })
- .catch((error) => {
- console.info("22222222222222222 error: " + JSON.stringify(error))
- })
- }
- }
HotKeyBean类
以上HttpLibaray库是基于Http的简单封装,如果添加其他属性及监听,可参考上面文档自行添加。
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。