#鸿蒙通关秘籍#如何在HarmonyOS Next中封装http请求

HarmonyOS
2024-12-03 13:03:30
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
GUI碧血丹心

在HarmonyOS Next中,通过Promise异步回调方式封装http请求,可以使用以下步骤完成:

  1. 创建resultVO接口,定义后端返回数据的格式。
export default interface resultVO<T>{
  code: number
  msg: string
  data: T
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  1. 创建requestParams接口,用于定义http请求的参数。
import { http } from '@kit.NetworkKit'

export interface requestParams{
  url: string
  method?: http.RequestMethod
  extraData?: object
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  1. 实现请求方法,发送http请求并返回一个Promise对象。
import { http } from '@kit.NetworkKit'
import resultVO from '../common/impl/resultVO'

export const request = async <T>(params: requestParams): Promise<resultVO<T>> => {
  const baseURL: string = 'http://192.168.31.160:8080';
  let httpRequest = http.createHttp();

  let requestUrl = baseURL + params.url;
  
  let options: http.HttpRequestOptions = {
    method: params.method ?? http.RequestMethod.GET,
    header: {
      'Content-Type': 'application/json',
      token: 'your-token-here'
    },
    extraData: params.extraData ?? undefined,
    expectDataType: http.HttpDataType.OBJECT
  }

  return new Promise(async (resolve, reject) => {
    httpRequest.request(
      requestUrl,
      options,
      (err, data) => {
        if (!err) {
          const res = data.result as resultVO<T>
          
          if(res.code == 1) {
            resolve(res)
          } else {
            console.error('Error:', res.msg)
          }
        } else {
          console.error('error:', JSON.stringify(err))
          reject(err)
        }

        httpRequest.destroy()
      }
    )
  })
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
分享
微博
QQ
微信
回复
2024-12-03 14:29:52


相关问题
HarmonyOS http请求封装
901浏览 • 1回复 待解决
HarmonyOS http请求封装
949浏览 • 1回复 待解决
HarmonyOS http网络请求封装的Demo
908浏览 • 1回复 待解决