【HarmonyOS】鸿蒙开发之HTTP网络请求——第5章

HTTP网络请求封装

network/request.ets

bash 复制代码
import { configInterface } from './type'
import http from '@ohos.net.http'
import { getToken } from '../utils/storage'

//网络请求封装
export const request = (config:configInterface)=>{
  let httpRequest:http.HttpRequest = http.createHttp()
  let method:http.RequestMethod = config.method.toLowerCase()=='get'?http.RequestMethod.GET:http.RequestMethod.POST
  let header = {}
  let Token = getToken()
  if(config.headers){
    header={
      ...config.headers,
      'X-CSRF-TOKEN': `VueCms_xg ${Token}`,
      'Authorization': `Bearer vuecms.cn`,
    }
  }else if(!config.headers){
    config.headers={
      "Content-Type": "application/json"
    }
  }
  console.log('http://localhost:3000' + config.url,"32333333333");
  let response = httpRequest.request(
    // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
    // config.url,
    "http://localhost:3000"+config.url,
    {
      method, // 可选,默认为http.RequestMethod.GET
      // 开发者根据自身业务需要添加header字段
      header,
      extraData:{...config.data},
      expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
    });
  return response.then((res:any)=>{
    let resultData:any = {}
    // 取消订阅HTTP响应头事件
    httpRequest.off('headersReceive');
    // 当该请求使用完毕时,调用destroy方法主动销毁
    httpRequest.destroy();

    let result:any = JSON.parse(res.result);
    console.log(result.code);
    if (result.code === 403) {
      console.log("登录状态已过期,您可以继续留在该页面,或者重新登录");
      // model.handleMsgBox('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
      //   confirmButtonText: '重新登录',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   userStore.LogOut().then(() => {
      //     location.href = "/login";
      //   })
      // })
    }
    resultData = {
      code:result.code,
      data:result.data,
      message:result.message,
    }
    return Promise.resolve(resultData)
  }).catch(err=>{
    console.log(JSON.stringify(err),"errrrrr111rrr");
    // 取消订阅HTTP响应头事件
    httpRequest.off('headersReceive');
    // 当该请求使用完毕时,调用destroy方法主动销毁。
    httpRequest.destroy();
    return new Promise((resolve,reject)=>{
      let res = {
        code:err.code,
        data:"",
        message:err.message,
      }
      reject(res)
    })
  })
}

network/type/index.ts 网络请求文件的typescript文件

bash 复制代码
export type methodsData = "post" | "get"
interface downloadParamsInterface{
  url: string
  params?: any
  filename: string
  isPost?: boolean
}
export interface configInterface{
  url: string
  data?: any
  method?: methodsData
  headers?: any
  downloadData?:downloadParamsInterface
}
export interface responseInterface {
  data:any
  message:string
  code:Number
}

实战项目使用

登录页的网络请求文件

ets/network/login/index.ts

登录页使用

ets/pages/login/index.ets

注意:

  1. 浏览器暂不支持网络请求,只能在模拟器或真机进行
  2. 请求需要申请ohos.permission.INTERNET 权限
  3. 网络请求限定并发个数为100,超过这一限制的后续请求会失败。
  4. 默认支持https ,如果要支持http,需要在module.json5 里添加network 标签

✨ 踩坑不易,还希望各位大佬支持一下 \textcolor{gray}{踩坑不易,还希望各位大佬支持一下} 踩坑不易,还希望各位大佬支持一下

📃 个人主页: \textcolor{green}{个人主页:} 个人主页: 沉默小管

📃 个人网站: \textcolor{green}{个人网站:} 个人网站: 沉默小管

📃 个人导航网站: \textcolor{green}{个人导航网站:} 个人导航网站: 沉默小管导航网

📃 我的开源项目: \textcolor{green}{我的开源项目:} 我的开源项目: vueCms.cn

🔥 技术交流 Q Q 群: 837051545 \textcolor{green}{技术交流QQ群:837051545} 技术交流QQ群:837051545

👍 点赞,你的认可是我创作的动力! \textcolor{green}{点赞,你的认可是我创作的动力!} 点赞,你的认可是我创作的动力!

⭐️ 收藏,你的青睐是我努力的方向! \textcolor{green}{收藏,你的青睐是我努力的方向!} 收藏,你的青睐是我努力的方向!

✏️ 评论,你的意见是我进步的财富! \textcolor{green}{评论,你的意见是我进步的财富!} 评论,你的意见是我进步的财富!

如果有不懂可以留言,我看到了应该会回复

如有错误,请多多指教

相关推荐
Deryck_德瑞克1 小时前
Java网络通信—TCP
java·网络·tcp/ip
GodK7771 小时前
IP 数据包分包组包
服务器·网络·tcp/ip
梁诚斌1 小时前
VSOMEIP代码阅读整理(1) - 网卡状态监听
运维·服务器·网络
ZachOn1y2 小时前
计算机网络:计算机网络概述 —— 描述计算机网络的参数
网络·tcp/ip·计算机网络·考研必备
我命由我123452 小时前
SSL 协议(HTTPS 协议的关键)
网络·经验分享·笔记·学习·https·ssl·学习方法
两点王爷3 小时前
使用WebClient 快速发起请求(不使用WebClientUtils工具类)
java·网络
wusam3 小时前
螺蛳壳里做道场:老破机搭建的私人数据中心---Centos下Docker学习03(网络及IP规划)
运维·服务器·网络·docker·容器
什么鬼昵称5 小时前
Pikachu-xxe-xxe漏洞
网络·安全·xxe
zhongcx6 小时前
鸿蒙应用示例:ArkTS UI框架中的文本缩进技巧
harmonyos