当前位置:   article > 正文

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

鸿蒙自定义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类中添加对外输出的引用

  1. export { HttpManager } from './src/main/ets/HttpManager'
  2. export { RequestMethod } from './src/main/ets/http/RequestMethod'
HttpCore类:
  1. import http from '@ohos.net.http';
  2. import { RequestOptions } from './RequestOptions';
  3. /**
  4. * Http请求器
  5. */
  6. export class HttpCore {
  7. /**
  8. * 发送请求
  9. */
  10. request<T>(requestOption: RequestOptions): Promise<T> {
  11. return new Promise<T>((resolve, reject) => {
  12. this.sendRequest(requestOption)
  13. .then((response) => {
  14. if (typeof response.result !== 'string') {
  15. reject(new Error('Invalid data type'));
  16. } else {
  17. let bean: T = JSON.parse(response.result);
  18. if (bean) {
  19. resolve(bean);
  20. } else {
  21. reject(new Error('Invalid data type,JSON to T failed'));
  22. }
  23. }
  24. })
  25. .catch((error) => {
  26. reject(error);
  27. });
  28. });
  29. }
  30. private sendRequest(requestOption: RequestOptions): Promise<http.HttpResponse> {
  31. // 每一个httpRequest对应一个HTTP请求任务,不可复用
  32. let httpRequest = http.createHttp();
  33. let resolveFunction, rejectFunction;
  34. const resultPromise = new Promise<http.HttpResponse>((resolve, reject) => {
  35. resolveFunction = resolve;
  36. rejectFunction = reject;
  37. });
  38. if (!this.isValidUrl(requestOption.url)) {
  39. return Promise.reject(new Error('url格式不合法.'));
  40. }
  41. let promise = httpRequest.request(requestOption.url, {
  42. method: requestOption.method,
  43. header: requestOption.header,
  44. extraData: requestOption.extraData, // 当使用POST请求时此字段用于传递内容
  45. expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
  46. readTimeout: requestOption.readTimeout ? requestOption.readTimeout : 60000,
  47. connectTimeout: requestOption.connectTimeout ? requestOption.connectTimeout : 60000
  48. });
  49. promise.then((response) => {
  50. console.info('Result:' + response.result);
  51. console.info('code:' + response.responseCode);
  52. console.info('header:' + JSON.stringify(response.header));
  53. if (http.ResponseCode.OK !== response.responseCode) {
  54. throw new Error('http responseCode !=200');
  55. }
  56. resolveFunction(response);
  57. }).catch((err) => {
  58. rejectFunction(err);
  59. }).finally(() => {
  60. // 当该请求使用完毕时,调用destroy方法主动销毁。
  61. httpRequest.destroy();
  62. })
  63. return resultPromise;
  64. }
  65. /**
  66. * 判断Url格式是否合法
  67. */
  68. private isValidUrl(url: string): boolean {
  69. return url.startsWith("http://") || url.startsWith("https://");
  70. }
  71. }
  72. export const httpCore = new HttpCore();
RequestMethod类
  1. export enum RequestMethod {
  2. OPTIONS = "OPTIONS",
  3. GET = "GET",
  4. HEAD = "HEAD",
  5. POST = "POST",
  6. PUT = "PUT",
  7. DELETE = "DELETE",
  8. TRACE = "TRACE",
  9. CONNECT = "CONNECT"
  10. }
RequestOptions类
  1. import { RequestMethod } from './RequestMethod';
  2. /**
  3. *
  4. * 网络请求配置
  5. */
  6. export interface RequestOptions {
  7. /**
  8. * 请求的url.
  9. */
  10. url?: string;
  11. /**
  12. * 请求的方法,默认GET.
  13. */
  14. method?: RequestMethod;
  15. /**
  16. * 请求的其他数据
  17. * extraData can be a string or an Object (API 6) or an ArrayBuffer(API 8).
  18. */
  19. extraData?: string | Object | ArrayBuffer;
  20. /**
  21. * HTTP 请求头,默认值:'content-type': 'application/json'
  22. */
  23. header?: Object;
  24. /**
  25. *读取超时时间 单位毫秒 默认60000ms
  26. */
  27. readTimeout?: number;
  28. /**
  29. *连接超时时间 单位毫秒 默认60000ms
  30. */
  31. connectTimeout?: number;
  32. }
HttpManager类
  1. import { RequestOptions } from './http/RequestOptions';
  2. import { httpCore as HttpCore } from './http//HttpCore';
  3. /**
  4. * Http对外管理器
  5. */
  6. export class HttpManager {
  7. private static mInstance: HttpManager;
  8. // 防止实例化
  9. private constructor() {
  10. }
  11. static getInstance(): HttpManager {
  12. if (!HttpManager.mInstance) {
  13. HttpManager.mInstance = new HttpManager();
  14. }
  15. return HttpManager.mInstance;
  16. }
  17. request<T>(option: RequestOptions): Promise<T> {
  18. return HttpCore.request(option);
  19. }
  20. }

3、在Entry中引用HttpLibaray

参考链接:静态har共享包

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

  1. "dependencies": {
  2. "@app/HttpLibrary": "file:../HttpLibrary"
  3. }

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

4、代码调用

  1. import { HttpManager, RequestMethod } from "@app/HttpLibrary"
  2. import { HotKeyBean, DataBean } from '../bean/HotKeyBean';
  3. @Entry
  4. @Component
  5. struct Index {
  6. @State message: string = '';
  7. build() {
  8. Row() {
  9. Column() {
  10. Text(this.message)
  11. .fontSize(15)
  12. .fontWeight(FontWeight.Bold)
  13. Button("获取数据")
  14. .fontSize(30)
  15. .padding(15)
  16. .onClick(() => {
  17. this.getData()
  18. })
  19. }
  20. .width('100%')
  21. }
  22. .height('100%')
  23. }
  24. private getData(): void {
  25. HttpManager.getInstance()
  26. .request<HotKeyBean>({
  27. method: RequestMethod.GET,
  28. url: 'https://www.wanandroid.com/hotkey/json' //wanandroid的API
  29. })
  30. .then((result: HotKeyBean) => {
  31. console.info("22222222222222222 result: " + JSON.stringify(result))
  32. if (result.errorCode == 0) {
  33. var data: DataBean[] = result.data
  34. for (let i = 0; i < data.length; i++) {
  35. this.message = this.message + data[i].name + "\n"
  36. }
  37. }
  38. })
  39. .catch((error) => {
  40. console.info("22222222222222222 error: " + JSON.stringify(error))
  41. })
  42. }
  43. }

HotKeyBean类

以上HttpLibaray库是基于Http的简单封装,如果添加其他属性及监听,可参考上面文档自行添加。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/238615?site
推荐阅读
相关标签
  

闽ICP备14008679号