#鸿蒙通关秘籍#如何在HarmonyOS Next实现基于API11的HTTP请求封装与自动化Token管理?

HarmonyOS
2024-11-28 16:08:58
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
PixelPegasus

HarmonyOS Next的开发中,可以通过封装一个HTTP请求工具类,实现自动化管理Token以及封装请求流程。可以定义接口前缀、登录页面路由信息和接口参数类型,并将请求结果返回Promise对象。同时,从本地持久化中读取Token,在工具类文件中进行统一管理。

import http from '@ohos.net.http';
import { BusinessError } from '@ohos.base';
import promptAction from '@ohos.promptAction';
import { getToken } from './index';
import router from '@ohos.router';

const BASEURL: string = "https://xxxxxxx.com";
const LOGINPAGEURL = 'pages/common/login';

//定义接口参数数据类型
interface RequestParams {
  url: string;
  method?: http.RequestMethod;
  data?: Object;
  headerContentType?: string;
}

//实现接口请求返回数据的Result类
class ResponseResult {
  code: number;
  message: string;
  data: Object | null;

  constructor(code?: number, message?: string, data?: Object | null | undefined) {
    this.code = code ?? 0;
    this.message = message ?? '';
    this.data = data ?? null;
  }
}

export default function request(params: RequestParams): Promise<ResponseResult> {
  return new Promise(async (resolve: (res: ResponseResult) => void, reject: (res: ResponseResult | string | BusinessError | http.HttpResponse) => void) => {
    //定义请求的数据格式(默认application/json)
    let contentType: string = params.headerContentType || 'application/json';
    let requestData: Object | undefined = params.data;
    if (contentType === 'application/x-www-form-urlencoded') {
      if (typeof params.data === 'object') {
        requestData = Object.entries(requestData as object).reduce((prev: string, cur: Array<Object>) => {
          return (prev && `${prev}&`) + `${cur[0]}=${cur[1]}`;
        }, '');
      }
    }
    let token: string = await getToken(); //从本地存储获取token
    let httpRequest = http.createHttp();
    httpRequest.request(BASEURL + params.url, {
      method: params.method ?? http.RequestMethod.GET,
      header: {
        'Content-Type': contentType,
        token
      },
      extraData: requestData,
      readTimeout: 30000,
      connectTimeout: 30000
    }, (err: BusinessError, data: http.HttpResponse) => {
      if (!err) {
        if (data.responseCode === 200) {
          let res: ResponseResult = JSON.parse(`${data.result}`);
          let response = new ResponseResult(res.code, res.message, res.data);
          if (res.code === 200) {
            resolve(response);
          } else if (res.code === 401) {
            router.clear();
            router.replaceUrl({ url: LOGINPAGEURL });
          } else {
            showToast(response.message);
            reject(response);
          }
        } else {
          showToast();
          reject(data);
        }
      } else {
        showToast(err.message);
        reject(err);
      }
      httpRequest.off('headersReceive');
      httpRequest.destroy();
    });
  });
}

const showToast = (message?: string) => {
  promptAction.showToast({
    message: message || '请求出错',
    duration: 2000
  });
}

读取本地Token方法:

import dataPreferences from '@ohos.data.preferences';

export const getToken: Function = async () => {
  try {
    let preferences: dataPreferences.Preferences = await globalThis.getPreferences();
    return preferences.getSync('token', '');
  } catch (e) {
  }
  return '';
}

export const setToken: Function = async (value: string) => {
  try {
    let preferences: dataPreferences.Preferences = await globalThis.getPreferences();
    preferences.putSync('token', encodeURIComponent(value));
    await preferences.flush();
  } catch (e) {
    console.log(JSON.stringify(e), 'e');
  }
}

在需要使用的页面引入并调用:

import { getHomeData } from "../api/home";

@Entry
@Component
struct Home {
  aboutToAppear(): void {
     getHomeData({
      storeId: '17815455885'
    }).then(res => {
       console.log(JSON.stringify(res), '接口返回数据');
    });
  }
}
分享
微博
QQ
微信
回复
2024-11-28 15:41:06
相关问题
如何查看ArkTS api11 版本变动?
2137浏览 • 1回复 待解决
HarmonyOS 自动化打包脚本实现
118浏览 • 1回复 待解决
HarmonyOS API11限制使用标准库
430浏览 • 1回复 待解决
HarmonyOS 使用 api11 地图不显示
626浏览 • 1回复 待解决
HarmonyOS http请求封装
134浏览 • 1回复 待解决
HarmonyOS http请求封装
133浏览 • 1回复 待解决