返璞归真——HarmonyOS 网络请求工具库封装

文章介绍了HarmonyOS原生网络请求的复杂用法,并提出将其封装以提高开发效率。作者提供了EasyHttp类的封装示例,强调了在处理多个请求时HttpRequest对象的管理以及生态系统的成长潜力。
摘要由CSDN通过智能技术生成

前言

HarmonyOS 原生网络请求的用法比较麻烦,还是有必要封装下,先看它的原生写法:

// 引入包名
import http from '@ohos.net.http';

// 每一个httpRequest对应一个HTTP请求任务,不可复用
let httpRequest = http.createHttp();
// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
    // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
    "EXAMPLE_URL",
    {
        method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
        // 开发者根据自身业务需要添加header字段
        header: {
            'Content-Type': 'application/json'
        },
        // 当使用POST请求时此字段用于传递内容
        extraData: {
            "data": "data to send",
        },
        expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
        usingCache: true, // 可选,默认为true
        priority: 1, // 可选,默认为1
        connectTimeout: 60000, // 可选,默认为60000ms
        readTimeout: 60000, // 可选,默认为60000ms
        usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
    }, (err, data) => {
        if (!err) {
            // data.result为HTTP响应内容,可根据业务需要进行解析
            console.info('Result:' + JSON.stringify(data.result));
            console.info('code:' + JSON.stringify(data.responseCode));
            // data.header为HTTP响应头,可根据业务需要进行解析
            console.info('header:' + JSON.stringify(data.header));
            console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
            // 取消订阅HTTP响应头事件
            httpRequest.off('headersReceive');
            // 当该请求使用完毕时,调用destroy方法主动销毁
            httpRequest.destroy();
        } else {
            console.info('error:' + JSON.stringify(err));
            // 取消订阅HTTP响应头事件
            httpRequest.off('headersReceive');
            // 当该请求使用完毕时,调用destroy方法主动销毁。
            httpRequest.destroy();
        }
    }
);

这么一大挂,怎么看也不像 axios 那样 axios.get(url) 一行代码就能够请求了。原生的HarmonyOS 网络请求可能更偏向于提供底层功能,类似于 WEB 中的 XMLHttpRequest,对于前端比较习惯的可能是下面的方式:

import http from '../utils/http'

export const login = (params: any) => http.postForm('/api/example/login', params)

export const login2 = (params: any) => http.postJson('/api/example/login', params)

export const login3 = (params: any) => http.get('/api/example/login', params)

login({}).then(res => {
	// ...
})

简洁,非常简洁~ 下面我们来看看是怎么封装的。

封装

interface EasyHttpOptions {
  baseUrl?: string
  connectTimeout?: number
  readTimeout?: number
}

class EasyHttp {
  protected options: EasyHttpOptions = {
    baseUrl: '',
    connectTimeout: 6 * 1000,
    readTimeout: 6 * 1000
  }

  constructor(options: EasyHttpOptions = {}) {
    Object.assign(this.options, options)
  }

  request(url: string, options: http.HttpRequestOptions = {}) {
    const {baseUrl, connectTimeout, readTimeout} = this.options
    const httpRequest = http.createHttp()

    return new Promise<http.HttpResponse>((resolve, reject) => {
      httpRequest.request(
        baseUrl + url,
        {
          expectDataType: http.HttpDataType.OBJECT, // 可选,指定返回数据的类型
          connectTimeout, // 可选,默认为60000ms
          readTimeout, // 可选,默认为60000ms
          ...options
        }
      ).then(res => {
        if (res.code === 200) {
          const { code } = (res.result || {}) as any
          if (code === 0) {
            resolve(res)
          } else {
            reject(res)
          }
        } else {
          reject(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  }

  get(url: string, params: Record<string, any> = {}, options: http.HttpRequestOptions = {}) {
    return this.request(`${url}?${stringify(params)}`, {
      method: http.RequestMethod.GET,
      ...options
    })
  }

  postForm(url: string, data: Record<string, any>, options: http.HttpRequestOptions = {}) {
    return this.request(url, {
      method: http.RequestMethod.POST,
      extraData: stringify(data),
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      ...options
    })
  }

  postJson(url: string, data: Record<string, any>, options: http.HttpRequestOptions = {}) {
    return this.request(url, {
      extraData: data,
      method: http.RequestMethod.POST,
      header: {
        'Content-Type': 'application/json'
      },
      ...options
    })
  }
}

export default new EasyHttp({
  baseUrl: 'https://demo.example.com'
})

上面有个序列化方法 stringify 如下:

function stringify(obj: Record<string, any>) {
  return Object.keys(obj)
    .map((key) => `${key}=${encodeURIComponent(obj[key])}`)
    .join('&')
}

以上封装属于业务层的常规封装,值得注意的是:

每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。最多只能创建100个HttpRequest对象。

正因如此,它才更有封装的必要性。

用法

const http = new EasyHttp({
  baseUrl: 'https://demo.example.com'
})

export const login = (params: any) => http.postForm('/api/example/login', params)

总结

尽管 HarmonyOS 开发生态(例:ohpm)目前尚显薄弱,但这正是我们展现创造力的绝佳时机。每个成熟的生态系统都需经历从无到有的过程,HarmonyOS 也不例外。希望 HarmonyOS 开发生态未来会更好,也希望会有更多的开发者能参与生态建设!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

帝尊菜鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值