6、HTTP 请求封装

1、封装http 工具类



import { HKBasePch } from '../PCH/HKPCH';
import { authHeaderSign } from './authHeaderSign';
import deviceInfo from '@ohos.deviceInfo';
import http from '@ohos.net.http';
import { Logger } from '@hzw/logger';


export class httpAxios {

  //HttpResponse
  public static async bodyPost(params: Map<string, object>,url:string, resultBlock:(res:http.HttpResponse) => void) {
    // 拼接设备基础参数
    let p = createHttp(params)
    
    Logger.w("传参  ======")
    console.dir(p)

    // 拼接url 域名
    let baseUrl = HKBasePch.Base_URL.toString() + url

    let resp = await http.createHttp()
      .request(baseUrl,await httpAxios.createParams(p))

    Logger.w("返回参数: ====== ")
    console.dir(resp.result)

    resultBlock(resp)

    // if (resp.responseCode == http.ResponseCode.OK){
    //     resultBlock(resp)
    // }else{
    //    resultBlock(resp)
    // }

  }


  /**
   * 设置Header 和 超时时间
   * */
  public static async createParams(params: Map<string, object>): Promise<http.HttpRequestOptions> {
    let p = createHttp(params)
    let header: Map<string, string> = new Map();
    header.set('Content-Type', 'application/json')
    header.set('Authorization', authHeaderSign.authSign(JSON.stringify(p)))

    Logger.w("鉴权信息: Authorization  ======")

    console.dir(authHeaderSign.authSign(JSON.stringify(p)))

    let options: http.HttpRequestOptions = {
      method: http.RequestMethod.POST,
      extraData: p,
      expectDataType: http.HttpDataType.OBJECT,
      header: {
        'Content-Type': 'application/json',
        'Authorization': authHeaderSign.authSign(JSON.stringify(p))
      },
      // 可选,默认为60s
      connectTimeout: 30000,
      // 可选,默认为60s
      readTimeout: 30000,
      usingProxy: true,

    }
    return options
  }

}

function createHttp(map?: Map<string, object>) {
  let params: Map<string, object>;
  if (map == null) {
    params = new Map<string, object>();
  } else {
    params = map;
  }
  params["zyOs"] = "hmOS";
  params["zyOsVersion"] = deviceInfo.displayVersion;
  params["zyModel"] = deviceInfo.productModel;
  params["zyBrand"] = deviceInfo.brand;
  params["abiList"] = deviceInfo.abiList;
  params["osFullName"] = deviceInfo.osFullName;
  params["deviceType"] = deviceInfo.deviceType;


  return params;
}


2、调用方法

 httpAxios.bodyPost(params,url,(rep) =>{

      if (rep.responseCode == http.ResponseCode.OK){
      }else{
      }

    })

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容