站长是什么职位,全屏网站表现形式,淮安网站开发工程师招聘网,wordpress显示作者墙目录 前言http网络库组件介绍http网络库封装创建Har Module创建RequestOption 配置类创建HttpCore核心类创建HttpManager核心类对外组件导出添加网络权限 http网络库依赖和使用依赖http网络库#xff08;httpLibrary#xff09;使用http网络库#xff08;httpLibrary#x… 目录 前言http网络库组件介绍http网络库封装创建Har Module创建RequestOption 配置类创建HttpCore核心类创建HttpManager核心类对外组件导出添加网络权限 http网络库依赖和使用依赖http网络库httpLibrary使用http网络库httpLibrary 前言
现在网上的应用基本都是网络应用需要进行联网获取数据而常用的联网获取数据的方式有http、socket、websocket等。
在鸿蒙应用、服务中stage模式开发下鸿蒙官方为我们提供了一个网络组件库 http ,我们通过
import http from ‘ohos.net.http’; 即可以完成引用。
http网络库组件介绍
ohos.net.http (数据请求) 该组件提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。 具体查看官网 通过官网的介绍可以很快上手该组件的使用下面我们对该网络库进行简单的封装方便我们的使用
http网络库封装
网络库工程结构如下图 具体步骤如下
创建Har Module创建RequestOption请求配置类创建HttpCore核心类创建HttpManager对外管理类对外组件导出添加网络权限
创建Har Module
我们创建一个Module 类型选择为Har3.1Beta IDE选择 Visual Library这里我们创建module名称为
httpLibrary。
创建RequestOption 配置类
代码如下
/*** pre* desc : 网络请求配置* /pre*/
export interface RequestOptions {/*** Request url.*/url?: string;/*** Request method.*/method?: RequestMethod; // default is GET/*** Request url queryParams .*/queryParams ?: Recordstring, 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
}这里字段大家可自行拓展我这里简单添加了几个常用字段包括url、urlParams、header、extraData、大家也可以增加一些诸如UserAgent之类的网络配置。
创建HttpCore核心类
该类使我们这个网络库的主要核心代码实现主要封装’ohos.net.http的API调用提供便捷使用的API。
import http from ohos.net.http;
import { RequestOptions } from ./RequestOptions;/*** Http请求器*/
export class HttpCore {/*** 发送请求* param requestOption* returns Promise*/requestT(requestOption: RequestOptions): PromiseT {return new PromiseT((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): Promisehttp.HttpResponse {// 每一个httpRequest对应一个HTTP请求任务不可复用let httpRequest http.createHttp();let resolveFunction, rejectFunction;const resultPromise new Promisehttp.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, // 当使用POST请求时此字段用于传递内容expectDataType: http.HttpDataType.STRING // 可选指定返回数据的类型});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;}private appendQueryParams(url: string, queryParams: Recordstring, string): string {// todo 使用将参数拼接到url上return url;}private isValidUrl(url: string): boolean {//todo 实现URL格式判断return true;}
}export const httpCore new HttpCore();
代码讲解
expectDataType: http.HttpDataType.STRING这里固定了返回数据为string大家也可以通过RequestOptions中定义字段传入这里定义为string只是方便后续的string转Bean定义sendRequest方法。对请求配置进行处理这里进行对Url进行格式判断如果非正确格式需要对外抛出错误需要进行Url参数拼接可对请求参数、请求结果进行日志打印对Http响应码进行判断按200和非200请求码进行分类返回。定义 request 进行请求结果转Bean的处理这里默认返回数据为JSON 字符串其他类型自行拓展该方法也是对外的唯一函数。
创建HttpManager核心类
import { RequestOptions } from ./RequestOptions;
import { httpCore as HttpCore } from ./HttpCore;
/*** pre* desc : 对外管理器* /pre*/
export class HttpManager {private static mInstance: HttpManager;// 防止实例化private constructor() {}static getInstance(): HttpManager {if (!HttpManager.mInstance) {HttpManager.mInstance new HttpManager();}return HttpManager.mInstance;}requestT(option: RequestOptions): PromiseT {return HttpCore.request(option);}
}
HttpManager 为对外API调用入口类提供单例对象跟发送请求API。
对外组件导出
在httpLibrary模块的根目录下有一个 index.ets文件在该文件中进行需要对外导出的组件定义 export { HttpManager } from ./src/main/ets/http/HttpManager;
export { RequestMethod } from ./src/main/ets/http/RequestOptions;
到这里我们就完成了一个简易的网络库封装我们可以将该module导出Har包对外提供也可以直接在项目中使用该module。
添加网络权限
漏了一点这里记得为该网络库添加上网络权限哦在module.json5文件中 requestPermissions: [{name: ohos.permission.INTERNET}]http网络库依赖和使用
依赖http网络库httpLibrary
打开entry下的 oh-package.json5文件增加如下依赖
dependencies: {ohos/http_library: file:../httpLibrary}使用http网络库httpLibrary
这里我们写一个例子使用该网络库进行发送一个get请求 在entry下任意页面中进行请求调用。
handleClick() {HttpManager.getInstance().requestTestBean({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 是一个公开的get请求API如果侵权请联系我删除谢谢 这里我们定一个了一个TestBean进行数据解析
/*** pre* desc : 测试Bean* /pre*/
export interface TestBean {/*** {userId: 1,id: 1,title: delectus aut autem,completed: false}*/userId: number,id: number,title: string,completed: boolean}
这样就完成了调用接着我们将应用装机点击获取数据按钮可以在log面板看到如下输出 文章到此结束需要Demo的或者是有问题交流的欢迎评论区留言。