【HarmonyOS Next】多线程网络请求简单封装

import http from '@ohos.net.http';
import { taskpool } from '@kit.ArkTS';

export class Request{

  static async get(url:string, header?: Object, expectDataType: http.HttpDataType = http.HttpDataType.OBJECT ): Promise<Object>{
    return await taskpool.execute(baseRequest, url, http.RequestMethod.GET, header,null, expectDataType);
  }

  static async post(url:string, header?: Object,extraData?: string | Object | ArrayBuffer, expectDataType: http.HttpDataType = http.HttpDataType.OBJECT): Promise<Object>{
    return await taskpool.execute(baseRequest, url, http.RequestMethod.POST, header, extraData, expectDataType);
  }
}

@Concurrent
async function baseRequest(url:string, method:http.RequestMethod, header?: Object, extraData?: string | Object | ArrayBuffer, expectDataType?: http.HttpDataType, connectTimeout?: number,multiFormDataList?: Array<http.MultiFormData>): Promise<http.HttpResponse>{

  console.info(`【http】baseRequest method:${method.toString()} , url:${url}, header:${JSON.stringify(header)}`);
  let httpRequest = http.createHttp();
  let res = await httpRequest.request(
    // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
    url,
    {
      method: method,  // 可选,默认为http.RequestMethod.GET
      header: header,  // 开发者根据自身业务需要添加header字段
      extraData: extraData, // 当使用POST请求时此字段用于传递内容
      expectDataType: expectDataType, // 可选,指定返回数据的类型
      usingCache: false, // 可选,默认为true
      priority: 1,       // 可选,默认为1
      connectTimeout: connectTimeout, // 可选,默认为60000ms
      readTimeout: 30000, // 可选,默认为60000ms
      multiFormDataList:multiFormDataList
    });
  httpRequest.destroy();
  console.info(`【http】baseRequest response:${res.responseCode} , url:${url}, data:${JSON.stringify(res.result)}`);
  return res;
}
posted @ 2024-05-08 13:58  七夜i  阅读(444)  评论(0编辑  收藏  举报