ArkTS网络请求

在尝试HarmonyOS应用开发的时候需要用到网络请求调取接口数据,随手封装了一个可复用的ArkTS网络请求(半成品),不一定好,但是能用,这里来解释一下代码的部分,interface baseHeader用于给请求头封装时间戳,随机数,签名等用于与api接口交互验证身份,其余的代码如下:

import http from '@ohos.net.http';
import { ApiBaseUrl, ApiBaseUrl1 } from "./config";
import { data } from '../data/interface';

interface BaseHeader {
  'TIMESTAMP': string;
  'RANDOMSTR': string;
  'SIGNATURE': string;
  'CLIENT': string;
  'Authorization'?: string;
};

// 定义请求头
const createHeaders = (): BaseHeader => {
  const headers: BaseHeader = {
    "TIMESTAMP": 'a',
    "RANDOMSTR": 'b',
    "SIGNATURE": 'c',
    'CLIENT': 'd',
  };

  // 检查是否有用户登录后的token,有则在header中携带
  const token = AppStorage.Get('token');
  if (token) {
    headers.Authorization = "jwt " + token;
  }

  return headers;
};

// 定义通用的API请求函数
export default async function api(
  method: 'GET' | 'POST',
  url: string,
  data?: data,
  useDefault: boolean = true
): Promise<data | null> {
  let result: data | null = null;
  const httpRequest: http.HttpRequest = http.createHttp();
  const completeUrl: string = useDefault ? ApiBaseUrl + url : ApiBaseUrl1 + url;

  // 封装options
  const options: http.HttpRequestOptions = {
    method: method === 'GET' ? http.RequestMethod.GET : http.RequestMethod.POST,
    header: createHeaders(),
  };

  if (data) {
    options.extraData = data;
  }

  try {
    const response = await httpRequest.request(completeUrl, options);

    if (response.responseCode === 200) {
      result = typeof response.result === 'string' ? JSON.parse(response.result) : response.result;
    } else {
      // TODO: 对于更多状态码的处理
      console.error(`Error: Received status code ${response.responseCode}`);
    }
  } catch (err) {
    // 请求失败,进行失败逻辑处理
    console.error('Request failed', err);
  }

  return result;
}

页面中调用方法如下,可以通过async/await来等待数据请求的完成,这里只是基于Hello World页面做的一个演示demo:

import api from '../common/api';
import apiUrl from '../common/api_url';
import { data } from '../data/interface'

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State page: number = 1;
  @State res: data = {};
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button('调用数据', { type: ButtonType.Capsule, stateEffect: true })
          .onClick(async () => {
            const data = {
              use_last_asking: true,
              page_size: 12,
              page: this.page,
            };
            this.page += 1;
            this.res = await api('GET', apiUrl.postList, data);
            console.log('count:', this.res.count);
          })
      }.justifyContent(FlexAlign.Center)
      .width('100%')
    }
    .height('100%')
  }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值