鸿蒙Axios请求框架核心代码整理

请求

import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios';
import { mmkvInfoUtil } from '../../../../../Index';
import { IHttpRequest, RequestMethod } from '../interface/IHttpRequest';
import { IHttpResponse } from '../interface/IHttpResponse';

export class HttpRequest implements IHttpRequest {
  private url: string | undefined
  private params?: Record<string, object | string | number>
  private httpResp: IHttpResponse | undefined
  private requestMethod: RequestMethod = RequestMethod.GET
  //axios的实例
  private instance: AxiosInstance;

  constructor(config: InternalAxiosRequestConfig) {
    //axios请求配置
    this.instance = axios.create(config)
    //拦截器
    this.initInterceptors();
  }

  setRequestMethod(requestMethod: RequestMethod): void {
    this.requestMethod = requestMethod;
  }

  setUrl(url: string): void {
    this.url = url;
  }

  setParams(params: Record<string, object | string | number>): void {
    this.params = params;
  }

  execute() {
    if (this.requestMethod == RequestMethod.POST) {
      //post请求
      this.instance.post(this.url, JSON.stringify(this.params))
        .then((response: AxiosResponse) => {
          this.httpResp?.onResponse(JSON.stringify(response));
        });
    } else {
      //get请求
      this.instance.get(this.url, { params: JSON.stringify(this.params) })
        .then((response: AxiosResponse) => {
          this.httpResp?.onResponse(JSON.stringify(response));
        });
    }
  }

  setResponse(httpResponse: IHttpResponse): void {
    this.httpResp = httpResponse;
  }

  private initInterceptors() {
    this.instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {

      console.error("DianDianNetWork-->requestUrl:", config.baseURL +"   "+ (config.url == undefined ? "" : config.url));
      console.error("DianDianNetWork-->requestHeader:", config.headers);
      console.error("DianDianNetWork-->requestParameters:", config.params);
      return config
    }, (error: object) => {
      console.error("DianDianNetWork-->request-->error", error);
      return error;
    }
    )
    this.instance.interceptors.response.use((response: AxiosResponse) => {
      console.error("DianDianNetWork-->response  data", JSON.stringify(response.data));
      console.error("DianDianNetWork-->response  status", JSON.stringify(response.status));
      console.error("DianDianNetWork-->response  statusText", JSON.stringify(response.statusText));
      console.error("DianDianNetWork-->response  headers", JSON.stringify(response.headers));
      console.error("DianDianNetWork-->response  config", JSON.stringify(response.config));
      console.error("DianDianNetWork-->response  request", JSON.stringify(response.request));
      console.error("DianDianNetWork-->response  performanceTiming", JSON.stringify(response.performanceTiming));

      if (response.headers != undefined) {
        console.error("DianDianNetWork-->response 存储token1",JSON.stringify(response.headers))
        if(response.headers["set-cookie"] != undefined){
          console.error("DianDianNetWork-->response 存储token2",response.headers["set-cookie"])
          console.error("DianDianNetWork-->response 存储token3",response.headers["set-cookie"][0])
           if(response.headers["set-cookie"][0].startsWith("Tuwan_Passport")){
             mmkvInfoUtil.writeString("Cookie",response.headers["set-cookie"][0]);
             console.error("DianDianNetWork-->response 存储token成功");
           }
        }
      }
      return response.data
    }, (error: object) => {
      console.error("DianDianNetWork-->response-->error", error);
      return Promise.reject(error)
    })
  }
}

响应

import { IHttpResponse } from '../interface/IHttpResponse';

export class HttpResponse<T> implements IHttpResponse{

  constructor(onHandle?: (objResult: T) => void) {
    //负值给全局
    if(onHandle != null && onHandle != undefined){
      this.onHandle = onHandle;
    }
  }

  onResponse(result: string): void {
    //1.转换成对象
    let objRes: T = JSON.parse(result);
    this.onHandle(objRes);
  }

  //外部也可以直接传递
  onHandle:(objResult:T) =>void = (result:T) =>{}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值