鸿蒙自定义Http网络访问组件

前言

DevEco Studio版本:4.0.0.600

使用效果

如何使用

参考文档:OpenHarmony http数据请求

1、module创建

File-->New-->Module,选择Static Library

2、相关类创建

HttpCore:Http的核心类,用于http的请求

RequestMethod:http请求的类型,包含:GET、POST等

RequestOptions:http的请求配置,包含:请求的url、请求头等

HttpManager:Http请求的管理类

然后在HttpLibraryIndex.ets类中添加对外输出的引用

export { HttpManager } from './src/main/ets/HttpManager'

export { RequestMethod } from './src/main/ets/http/RequestMethod'
HttpCore类:
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();

RequestMethod类
export enum RequestMethod {
   OPTIONS = "OPTIONS",
   GET = "GET",
   HEAD = "HEAD",
   POST = "POST",
   PUT = "PUT",
   DELETE = "DELETE",
   TRACE = "TRACE",
   CONNECT = "CONNECT"
}
RequestOptions类
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;
}
HttpManager类
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);
   }
}

3、在Entry中引用HttpLibaray

参考链接:静态har共享包

Entry目录下的oh-package.json5文件中添加对HttpLibaray的引用,鼠标放在错误提示上出现Run "ohpm install",并执行以下。

"dependencies": {
  "@app/HttpLibrary": "file:../HttpLibrary"
}

执行完成后会在entry目录下的oh_moudles目录下出现HttpLibrary就说明引用成功了

4、代码调用

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的简单封装,如果添加其他属性及监听,可参考上面文档自行添加。

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

等风起了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值