HarmonyOS 鸿蒙Next 封装实现好用的网络模块

封装目的 网络模块使用的频率最高,也是最核心的一个模块。一个好用的网络模块是加快应用开发的神兵利器。虽然官方提供的 @ohos.net.http 模块功能强大,但直接使用不够便利。

如何让其像在类似 uni-app 中的 uni.request 那般好用?这里介绍一种封装实现,可以看到使用变得如此简单。同样的模块封装,之前博主已用在自己开发的影视应用中啦。

详见:uni-app 影视类小程序开发从零到一 | 开源项目分享 | uni.request-CSDN博客

这里效仿博主在 uni-app 中的使用经验,特实现以下模块化封装。

在封装网络模块组件之前,我们需要明确以下需求:

支持常见的 HTTP 请求方法:如 GET、POST、PUT、DELETE 等。 支持自定义请求头:允许开发者设置自定义的请求头。 支持请求拦截器:在请求发送前和响应返回后执行自定义逻辑。 支持错误处理:能够捕获并处理网络请求中的错误。 支持 Promise 和 async/await:方便异步操作。 实现步骤 创建网络模块组件 首先,我们创建一个名为 http.ts 的文件,用于封装网络模块组件。

// utils/http.ts

import http from '[@ohos](/user/ohos).net.http';

class Request {
  private httpClient: http.HttpRequest;
  public baseUrl: string;
  private url: string;
  public beforeRequest?: (request: Request) => void;
  public afterRequest?: (response: any) => void;
  private config: http.HttpRequestOptions;

  constructor(options: RequestOptions = {}) {
    this.config = {
      method: options.method || http.RequestMethod.GET,
      header: options.header || {},
      extraData: options.extraData || {},
      responseType: options.responseType || http.ResponseType.JSON,
      timeout: options.timeout || 10000
    };
    this.httpClient = http.createHttp();
    this.baseUrl = options.baseUrl || '';
    this.url = options.url || '';
    this.beforeRequest = options.beforeRequest;
    this.afterRequest = options.afterRequest;
    this.setupInterceptor();
  }

  /**
   * 配置属性拦截器
   */
  setupInterceptor() {
    // 这里可以添加拦截器内容
    this.config.requestInterceptor = (requestOptions: http.HttpRequestOptions) => {
      if (this.beforeRequest) {
        this.beforeRequest(this);
      }
      return requestOptions;
    };

    this.config.responseInterceptor = (response: any) => {
      if (this.afterRequest) {
        this.afterRequest(response.result);
      }
      return response;
    };
  }

  // 添加对 header 的支持
  private _mergeHeaders(customHeader: Record<string, string> = {}): Record<string, string> {
    return Object.assign({}, this.config.header, customHeader); // 合并默认 header 和自定义 header
  }

  get(url: string, data: Record<string, any> = {}): Promise<any> {
    this.config.method = http.RequestMethod.GET;
    this.config.extraData = data;
    this.url = this.baseUrl + url;
    return this._();
  }

  post(url: string, data: Record<string, any> = {}, header: Record<string, string> = {}): Promise<any> {
    this.config.method = http.RequestMethod.POST;
    this.config.extraData = data;
    this.config.header = this._mergeHeaders(header); // 合并 header
    this.url = this.baseUrl + url;
    return this._();
  }

  put(url: string, data: Record<string, any> = {}): Promise<any> {
    this.config.method = http.RequestMethod.PUT;
    this.config.extraData = data;
    this.url = this.baseUrl + url;
    return this._();
  }

  delete(url: string, data: Record<string, any> = {}): Promise<any> {
    this.config.method = http.RequestMethod.DELETE;
    this.config.extraData = data;
    this.url = this.baseUrl + url;
    return this._();
  }

  private _(): Promise<any> {
    // 发起请求
    return new Promise((resolve, reject) => {
      this.httpClient.request(
        this.url,
        this.config,
        (error, data) => {
          if (!error) {
            resolve(data.result);
          } else {
            reject(error);
          }
        }
      );
    });
  }
}

// 定义请求选项的类型
interface RequestOptions extends http.HttpRequestOptions {
  baseUrl?: string;
  url?: string;
  beforeRequest?: (request: Request) => void;
  afterRequest?: (response: any) => void;
}

export const $http = new Request();

添加请求拦截器 为了进一步增强网络模块组件的功能,我们可以在 Request 类的构造函数中添加请求和响应拦截器的配置。

setupInterceptor() {
  // 请求拦截器
  this.config.requestInterceptor = (requestOptions: http.HttpRequestOptions) => {
    if (this.beforeRequest) {
      this.beforeRequest(this);
    }
    return requestOptions;
  };

  // 响应拦截器
  this.config.responseInterceptor = (response: any) => {
    if (this.afterRequest) {
      this.afterRequest(response.result);
    }
    return response;
  };
}
配置权限
为了在 HarmonyOS 应用中使用网络请求,还需要在 config.json 文件中申请 ohos.permission.INTERNET 权限。

{
  "module": {
    "reqPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  }
}

如何使用 有了以上封装,使用就变得很简单啦,举例如下:

import { $http } from '../../utils/http';

interface Result {
  data: string;
}

$http.baseUrl = "http://175.178.126.10:8000"

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Column() {
      Text(this.message)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)

      Button('Test Request')
        .width(300)
        .margin({ top: 20 })
        .onClick(() => {
          const url = "/api/v1/swiperlist";

          $http.get(url).then((result: Result) => {
            console.log('Result:', result);
            this.message = result.data;
          }).catch((error: Error) => {
            console.error('Error:', error);
            this.message = 'Request failed!';
          });
        })
    }
    .width('100%')
    .height('100%')
  }
}

通过上述封装,我们可以轻松地在 HarmonyOS-NEXT 中实现便捷、高效的网络请求操作。希望本文对你有所帮助,欢迎在评论区分享你的经验和建议。


更多关于HarmonyOS 鸿蒙Next 封装实现好用的网络模块的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS 鸿蒙Next 封装实现好用的网络模块的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中封装一个好用的网络模块,基于最新5.0的API12,你可以参考以下步骤进行实现:

  1. 引入必要的模块: 在config.json文件中添加网络相关的模块依赖,例如ohos.network

  2. 创建网络工具类: 新建一个类,比如NetworkUtils,在其中封装网络请求的方法。

  3. 实现网络请求: 利用鸿蒙提供的网络API,如fetch接口,进行GET或POST请求。示例代码如下:

    import fetch from '[@ohos](/user/ohos).network.fetch';
    
    export class NetworkUtils {
        static async getRequest(url) {
            let response = await fetch.fetch({
                url: url,
                method: 'GET'
            });
            return await response.json();
        }
    
        static async postRequest(url, data) {
            let response = await fetch.fetch({
                url: url,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });
            return await response.json();
        }
    }
    
  4. 调用网络工具类: 在你的业务逻辑中,通过NetworkUtils类的方法发起网络请求。

以上步骤提供了一个基本的网络模块封装示例。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html。

回到顶部