鸿蒙next http网络请求工具类进阶版本来了

938 阅读5分钟

前言到读

消失了一段时间,这次也是参加社区的活动。所以准备重新写一些文章分享给大家, 今天分享是鸿蒙next 网络请求部分的, 之前分享了一个基于RCP 现在分享一个http 原理差不多 只是有部分差异 这个不影响各位学习整个思路

具体实现

这里我们主要讲究get 请求和post 请求 其他的还有put 请求和delete 请求用得相对较少有兴趣的同学可以查阅我们的官网的文档即可。

  • 1 创建请求的单例

public static instance: OkhttpUtils | null = null

// 设置方法为私有
private constructor() {

}

public static getInstance() {
  if (!OkhttpUtils.instance) {
    OkhttpUtils.instance = new OkhttpUtils()
  }
  return OkhttpUtils.instance
}
  • 2 定义接受map 参数方法 这里我们使用建造者模式


private parmasmap: Map<string, string> | undefined;

public parmas(map?: Map<string, string> | undefined): OkhttpUtils {
  this.parmasmap = map;
  return this;
}
  • 3 定义接受键值对参数方法 这里我们使用建造者模式

public addparmas(key: string, val: string): OkhttpUtils {
  if (this.parmasmap == null || this.parmasmap == undefined) {
    this.parmasmap = new Map<string, string>();
  }
  this.parmasmap.set(key, val)
  return this;
}
  • 4 定义get 请求方法


public httpRequestGet<T>(url: string): Promise<T|null> {
  return this.httpRequest(url, http.RequestMethod.GET);
}
  • 5 定义post 请求方法 (表单提交方式)


public httpRequestPost<T>(url: string): Promise<T|null> {
  return this.httpRequest(url, http.RequestMethod.POST);
}
  • 6 组装请求参数

let params: string = '';
let geturl: string = url;

if (method == http.RequestMethod.GET) {
  if (this.parmasmap != undefined && this.parmasmap != null) {
    geturl = geturl + "?" + Md5Utils.getInstance().getPostBodyFormParamMap(this.parmasmap);
    Logger.error("geturl" + geturl)
  }
} else {
  if (this.parmasmap != undefined && this.parmasmap != null) {
    params = Md5Utils.getInstance().getPostBodyFormParamMap(this.parmasmap); // 表单提交
  }
}
  • 7 创建 Request 实例

let httpRequest = http.createHttp();
  • 8 连接网络 设置请求和超时时间

let responseResult = httpRequest.request(geturl, {
  method: method,
  readTimeout: Constants.HTTP_READ_TIMEOUT, //读取超时时间可选  默认 600000
  header: {
    'Content-Type': ContentType.FORM_URLENCODED
  },
  connectTimeout: Constants.HTTP_READ_TIMEOUT, //连接超时时间  可选,默认为60000ms
  extraData: params // 请求参数
});
  • 9 处理响应返回

let  getjson:T|null=null;
return responseResult.then((value: http.HttpResponse) => {
  Logger.error("请求状态-- >" + value.responseCode);
  if (value.responseCode === 200) {
    Logger.error("请求成功");
    let result = `${value.result}`;
    Logger.error("请求返回数据", JSON.parse(result));
    getjson=JSON.parse(result) as T;
  } else {
    getjson = null;
  }
  return getjson;
}).catch(() => {
  httpRequest.destroy();
  return null;
});
  • post json方式提交请求参数
public httpRequestPostjson<T>(url: string, paramsjson?: string): Promise<T|null> {
  return this.httpRequestjson(url, http.RequestMethod.POST, paramsjson);
}


private httpRequestjson<T>(url: string, method: http.RequestMethod, params?: string): Promise<T|null> {
  let httpRequest = http.createHttp();
  let responseResult = httpRequest.request(url, {
    method: method,
    readTimeout: Constants.HTTP_READ_TIMEOUT, //读取超时时间可选  默认 600000
    header: {
      'Content-Type': ContentType.JSON
    },
    connectTimeout: Constants.HTTP_READ_TIMEOUT, //连接超时时间  可选,默认为60000ms
    extraData: params // 请求参数
  });

  let  getjson:T|null=null;
  return responseResult.then((value: http.HttpResponse) => {
    Logger.error("请求状态-- >" + value.responseCode);
    if (value.responseCode === 200) {
      Logger.error("请求成功");
      let result = `${value.result}`;
      Logger.error("请求返回数据", JSON.parse(result));
      getjson=JSON.parse(result) as T;
    } else {
      getjson = null;
    }
    return getjson;
  }).catch(() => {
    httpRequest.destroy();
    return null;
  });
}
  • 完整代码

import http from '@ohos.net.http';
import Constants, { ContentType } from './Constants';
import Logger from './Logger';
import { Md5Utils } from './Md5Utils';


/***
 *
 * 创建人:xuqing
 * 创建时间:2025年4月21日16:11:23
 * 类说明: 网络请求工具类
 *
 */


export class OkhttpUtils {
  public static instance: OkhttpUtils | null = null

  // 设置方法为私有
  private constructor() {

  }

  public static getInstance() {
    if (!OkhttpUtils.instance) {
      OkhttpUtils.instance = new OkhttpUtils()
    }
    return OkhttpUtils.instance
  }

  private parmasmap: Map<string, string> | undefined;

  public parmas(map?: Map<string, string> | undefined): OkhttpUtils {
    this.parmasmap = map;
    return this;
  }

  public addparmas(key: string, val: string): OkhttpUtils {
    if (this.parmasmap == null || this.parmasmap == undefined) {
      this.parmasmap = new Map<string, string>();
    }
    this.parmasmap.set(key, val)
    return this;
  }

  public httpRequestGet<T>(url: string): Promise<T|null> {
    return this.httpRequest(url, http.RequestMethod.GET);
  }


  public httpRequestPost<T>(url: string): Promise<T|null> {
    return this.httpRequest(url, http.RequestMethod.POST);
  }

  private httpRequest<T>(url: string, method: http.RequestMethod): Promise<T|null> {
    let params: string = '';
    let geturl: string = url;

    if (method == http.RequestMethod.GET) {
      if (this.parmasmap != undefined && this.parmasmap != null) {
        geturl = geturl + "?" + Md5Utils.getInstance().getPostBodyFormParamMap(this.parmasmap);
        Logger.error("geturl" + geturl)
      }
    } else {
      if (this.parmasmap != undefined && this.parmasmap != null) {
        params = Md5Utils.getInstance().getPostBodyFormParamMap(this.parmasmap); // 表单提交
      }
    }

    let httpRequest = http.createHttp();
    let responseResult = httpRequest.request(geturl, {
      method: method,
      readTimeout: Constants.HTTP_READ_TIMEOUT, //读取超时时间可选  默认 600000
      header: {
        'Content-Type': ContentType.FORM_URLENCODED
      },
      connectTimeout: Constants.HTTP_READ_TIMEOUT, //连接超时时间  可选,默认为60000ms
      extraData: params // 请求参数
    });


    let  getjson:T|null=null;
    return responseResult.then((value: http.HttpResponse) => {
      Logger.error("请求状态-- >" + value.responseCode);
      if (value.responseCode === 200) {
        Logger.error("请求成功");
        let result = `${value.result}`;
        Logger.error("请求返回数据", JSON.parse(result));
        getjson=JSON.parse(result) as T;
      } else {
        getjson = null;
      }
      return getjson;
    }).catch(() => {
      httpRequest.destroy();
      return null;
    });

  }

  public httpRequestPostjson<T>(url: string, paramsjson?: string): Promise<T|null> {
    return this.httpRequestjson(url, http.RequestMethod.POST, paramsjson);
  }


  private httpRequestjson<T>(url: string, method: http.RequestMethod, params?: string): Promise<T|null> {
    let httpRequest = http.createHttp();
    let responseResult = httpRequest.request(url, {
      method: method,
      readTimeout: Constants.HTTP_READ_TIMEOUT, //读取超时时间可选  默认 600000
      header: {
        'Content-Type': ContentType.JSON
      },
      connectTimeout: Constants.HTTP_READ_TIMEOUT, //连接超时时间  可选,默认为60000ms
      extraData: params // 请求参数
    });

    let  getjson:T|null=null;
    return responseResult.then((value: http.HttpResponse) => {
      Logger.error("请求状态-- >" + value.responseCode);
      if (value.responseCode === 200) {
        Logger.error("请求成功");
        let result = `${value.result}`;
        Logger.error("请求返回数据", JSON.parse(result));
        getjson=JSON.parse(result) as T;
      } else {
        getjson = null;
      }
      return getjson;
    }).catch(() => {
      httpRequest.destroy();
      return null;
    });
  }
}

具体调用

  • 链式调用通过addparmas 添加请求参数

OkhttpUtils.getInstance()
  .addparmas("username", "186740353353")
  .addparmas("password", "123456").httpRequestPost<LoginModel>(this.LOGIN).then((data) => {
  console.log("data-- >" + data?.msg);
  console.log("data-- >" + data?.code);
  console.log("data-- >" + data?.msg);

});
  • 通过map 的方式添加请求参数

OkhttpUtils.getInstance().parmas(map).httpRequestGet<LoginModel>(this.LOGIN).then((data) => {
  console.log("data-- >" + data?.msg);
  console.log("data-- >" + data?.code);
  console.log("data-- >" + data?.msg);

});
  • 不使用then 回调 map添加请求参数


let res=await  OkhttpUtils.getInstance().parmas(map).httpRequestGet<LoginModel>(this.LOGIN);
if(res?.code==200){
  Logger.error("res"+res.msg)
  Logger.error("res"+res.code)
  Logger.error("res"+res.user)
}
  • 不使用then 回调 链式调用通过addparmas 添加请求参数

let respost=await  OkhttpUtils.getInstance()
  .addparmas("username", "186740353353")
  .addparmas("password", "123456").httpRequestPost<LoginModel>(this.LOGIN);

if(respost?.code==200){
  Logger.error("respost"+respost.msg)
  Logger.error("respost"+respost.code)
  Logger.error("respost"+respost.user)
}

具体调用效果

image.png

我们通过日志截图里面的数据我们无论是用post或者get 都可以顺利请求到我们服务器的数据,并且我们定义了返回类型是泛型 我们在拿到服务器返回的数据的时候我们就直接解析调数据将json 解析格式化成为我们的model (class 或者 interface都可以 ) 我们在view层只需要直接获取我们的model里面属性即可

最后总结:

鸿蒙next 里面http 网络请求相对比较简单,但是这里只是简单提到了用法 ,例如还有拦截器还没有设置,这些希望同学们可以自己去完善 老师这边只是提供一个基本的思路,今天的文章就讲到这里有兴趣的同学可以拿老师代码去优化修改, 今天的文章就讲到这里有兴趣的 关注我B站教程 了解更多鸿蒙开发的知识 可以关注坚果派公众号 。 谢谢

课程地址

www.bilibili.com/cheese/play…

项目内容:

  • 1 常用布局组件的学习
  • 2 网络请求工具类封装
  • 3 arkui 生命周期启动流程
  • 4 日志工具类的封装
  • 5 自定义组合组件的封装
  • 6 路由导航跳转的使用
  • 7 本地地数据的缓存 以及缓存工具类的封装
  • 8 欢迎页面的实现
  • 9 登录案例和自动登录效果实现
  • 10 请求网络数据分页上拉加载 下拉刷新的实现
  • 11 list数据懒加载实现
  • 12 webview组件的使用

如果使用更多好用的鸿蒙next三方库

友情链接

harmony-utils 一款功能丰富且极易上手的HarmonyOS工具库,借助众多实用工具类,致力于助力开发者迅速构建鸿蒙应用,能够满足各种不同的开发需求。

harmony-dialog 一款极为简单易用的零侵入弹窗,仅需一行代码即可轻松实现,无论在何处都能够轻松弹出。