鸿蒙开辟-应用关照与提示、axios

打印 上一主题 下一主题

主题 994|帖子 994|积分 2982

关照

旨在让用户以合适的方式及时获得有效的新消息,资助用户高效地处置处罚任务。
应用可发送关照消息,用户在关照栏能查察关照内容,也可点击来打开应用。


  • 表现吸收到的短消息、即时消息
  • 表现应用的推送,如广告、版本更新
  • 表现当前正在进行的事件,如下载

一则关照



利用



  • notificationManager模块提供关照管理的能力,包罗发布、取消发布关照,创建、获取、移除关照通道等能力。
  • 基础类型关照应用于发送短信息、提示信息、广告推送等,支持平凡文本、长文本、多行文本,可以通过ContentType指定。
  1. import { notificationManager } from '@kit.NotificationKit';
  2. import { promptAction } from '@kit.ArkUI';
  3. @Entry
  4. @Component
  5. struct Index {
  6.   async notify(id:number, title: string, text: string){
  7.     try {
  8.       await notificationManager.requestEnableNotification()
  9.       let request: notificationManager.NotificationRequest = {
  10.         id: id,
  11.         content: {
  12.           notificationContentType:
  13.           notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
  14.           normal: {
  15.             title: title,
  16.             text: text
  17.           }
  18.         }
  19.       }
  20.       await notificationManager.publish(request)
  21.       promptAction.showToast({message:'发布成功!'})
  22.     } catch (e) {
  23.       promptAction.showToast({message:'发布失败:' + JSON.stringify(e)})
  24.     }
  25.   }
  26.   build() {
  27.     Column({space: 10}){
  28.       Button('发一个通知').onClick((event: ClickEvent) => {
  29.         this.notify(101, '鸿蒙NEXT训练营本周六课延期通知',
  30.           '各位同学好,原定本周六的课,改到周日下午4点到6点,敬请相互转告。')
  31.       })
  32.       Button('更新通知').onClick((event: ClickEvent) => {
  33.         this.notify(101, '鸿蒙NEXT训练营',
  34.           '各位同学好,下周课程按预定仍是周三周六。')
  35.       })
  36.       Button('取消通知').onClick((event: ClickEvent) => {
  37.         notificationManager.cancel(101)
  38.       })
  39.     }
  40.     .height('100%').width('100%')
  41.     .justifyContent(FlexAlign.Center)
  42.   }
  43. }
复制代码

更新一个关照

在发出关照后,利用您之前利用的雷同关照ID,再次调用notificationManager.publish来实现关照的更新。如果之前的关照是关闭的,将会创建新关照。
移除关照



  • 通过关照ID和关照标签取消已发布的关照: notificationManager.cancel(id)
  • 取消所有已发布的关照: notificationManager.cancelAll()
设置关照通道(SlotType)



  • SlotType.SOCIAL_COMMUNICATION:社交类型,状态栏中表现关照图标,有横幅和提示音。
  • SlotType.SERVICE_INFORMATION:服务类型,状态栏中表现关照图标,没有横幅但有提示音。
  • SlotType.CONTENT_INFORMATION:内容类型,状态栏中表现关照图标,但没有横幅或提示音。
  • SlotType.OTHER_TYPES:其它类型,状态栏中不表现关照图标,且没有横幅或提示音。
创建关照组

将不同类型的关照分为不同的组,以便用户可以更好的管理他们。当同组的关照有多条的时候,会主动折叠起来,避免关照比较多的时候,关照界面比较紊乱,比方当关照栏里有聊天消息关照和商品保举关照时,我们只需要通过设置字段groupName,就可以对关照进行分组,给groupName设置不同的值可以将关照分为不同的组。
后台代理提示

随着生存节奏的加快,我们偶然会忘记一些紧张的事变或日子,所以提示功能必不可少。应用可能需要在指定的时刻,向用户发送一些业务提示关照。
比方购物类应用,盼望在指定时间点提示用户有优惠活动。为满足此类业务诉求,HarmonyOS提供后台代理提示功能,在应用退居后台或退出后,计时和提示关照功能被体系后台代理接受。
axios

Axios是一个流行的网络请求库,运行在node.js和浏览器中。
OHPM版本基于原库做了适配,原用法和特性保持不变


  • http 请求
  • Promise API
  • request 和 response 拦截器
  • 转换 request 和 response 的 data 数据
  • 主动转换 JSON data 数据
安装:
ohpm install @ohos/axios
  1. /*
  2. * The MIT License (MIT)
  3. * Copyright (C) 2023 Huawei Device Co., Ltd.
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. */
  15. import axios, {
  16.   AxiosError,
  17.   AxiosResponse,
  18.   AxiosProgressEvent,
  19.   InternalAxiosRequestConfig,
  20.   AxiosRequestConfig
  21. } from '@ohos/axios'
  22. import { FormData } from '@ohos/axios'
  23. import fs from '@ohos.file.fs';
  24. import { IdModel, InfoModel, UploadModel } from '../types/types'
  25. import { DEMO_CONFIG, LOG } from '../common/Common'
  26. import { writeFile, readFile } from '../common/fileFs'
  27. axios.defaults.headers['authorization'] = 'customer-auto'
  28. axios.defaults.baseURL = DEMO_CONFIG.baseUrl
  29. const TAG = LOG.TAG
  30. @Entry
  31. @Component
  32. struct Index {
  33.   scroller: Scroller = new Scroller()
  34.   @State status: string | number = ''
  35.   @State message: string = ''
  36.   @State performanceTiming: string = '';
  37.   @State filename: string = 'blue.jpg'
  38.   @State progress: string = ''
  39.   @State downloadProgress: number = 0
  40.   @State uploadProgress: number = 0
  41.   @State showUrl: string = '';
  42.   @State connectTimeout: number = 0;
  43.   @State readTimeout: number = 0;
  44.   @State startTime: number = 0;
  45.   @State endTime: number = 0;
  46.   @State maxBodyLength: number = -1;
  47.   @State maxContentLength: number = -1;
  48.   baseUrl: string = DEMO_CONFIG.baseUrl;
  49.   getUrl: string = DEMO_CONFIG.getUrl;
  50.   postUrl: string = DEMO_CONFIG.postUrl;
  51.   putUrl: string = DEMO_CONFIG.putUrl;
  52.   deleteUrl: string = DEMO_CONFIG.deleteUrl;
  53.   downloadUrl: string = DEMO_CONFIG.downloadUrl;
  54.   uploadUrl: string = DEMO_CONFIG.uploadUrl;
  55.   clientCert_noPsw: string = DEMO_CONFIG.clientCert_noPsw;
  56.   clientCert_hasPsw: string = DEMO_CONFIG.clientCert_hasPsw;
  57.   proxyUrl: string = DEMO_CONFIG.proxyUrl;
  58.   psw: string = DEMO_CONFIG.psw;
  59.   host: string = DEMO_CONFIG.host;
  60.   controller = new TextInputController()
  61.   build() {
  62.     Scroll(this.scroller) {
  63.       Column() {
  64.         //axios标题
  65.         Text('axios使用案例 - 坚果派 张云波')
  66.           .fontSize(20)
  67.           .margin({ top: 10, bottom: 10 })
  68.         //请求按钮
  69.         Flex({
  70.           direction: FlexDirection.Row,
  71.           alignItems: ItemAlign.Start, wrap: FlexWrap.Wrap,
  72.           justifyContent:FlexAlign.SpaceAround
  73.         }) {
  74.           Button('Create').onClick((e) => {
  75.             this.create()
  76.           }).margin({ bottom:5 })
  77.           Button('Request').onClick((e) => {
  78.             this.request()
  79.           }).margin({ bottom:5 })
  80.           Button('Get').onClick((e) => {
  81.             this.get()
  82.           }).margin({ bottom:5 })
  83.           Button('Post').onClick((e) => {
  84.             this.post()
  85.           }).margin({ bottom:5 })
  86.           Button('Put').onClick((e) => {
  87.             this.put()
  88.           }).margin({ bottom:5 })
  89.           Button('Delete').onClick((e) => {
  90.             this.delete()
  91.           }).margin({ bottom:5 })
  92.           Button('拦截器').onClick((e) => {
  93.             this.interceptors()
  94.           }).margin({ bottom:5 })
  95.           Button('默认设置').onClick((e) => {
  96.             this.defaultSetting()
  97.           }).margin({ bottom:5 })
  98.           Button('下载').onClick((e) => {
  99.             this.download()
  100.           }).margin({ bottom:5 })
  101.           Button('上传').onClick((e) => {
  102.             this.upload()
  103.           }).margin({ bottom:5 })
  104.           Button('设置响应类型').onClick((e) => {
  105.             this.settingResponseType()
  106.           }).margin({ bottom:5 })
  107.           Button('设置代理').onClick((e) => {
  108.             this.settingProxy()
  109.           }).margin({ bottom:5 })
  110.           Button('双向校验(无密码)').onClick((e) => {
  111.             this.settingClientCert()
  112.           }).margin({ bottom:5 })
  113.           Button('双向校验(有密码)').onClick((e) => {
  114.             this.settingClientCert_psw()
  115.           }).margin({ bottom:5 })
  116.         }
  117.         //请求地址
  118.         Column() {
  119.           Text('网站:' + this.baseUrl)
  120.             .fontSize(14)
  121.             .fontWeight(FontWeight.Bold)
  122.             .margin({ bottom: 10 ,top: 10})
  123.           Row(){
  124.             Text('路径:')
  125.               .fontSize(14)
  126.             TextInput({text: this.showUrl})
  127.               .layoutWeight(1)
  128.           }.width('100%')
  129.         }
  130.         // .margin({ top: 10, bottom: 20 })
  131.         .alignItems(HorizontalAlign.Start)
  132.         //请求结果
  133.         Column() {
  134.           Text('结果')
  135.             .fontSize(14)
  136.             .fontWeight(FontWeight.Bold)
  137.             .margin({ bottom: 10 })
  138.             .textAlign(TextAlign.Start)
  139.           //进度条
  140.           if (this.showUrl === this.uploadUrl) {
  141.             Text('上传进度')
  142.             Progress({ value: this.uploadProgress, type: ProgressType.Linear })
  143.               .color('#009BE8').width('100%')
  144.               .margin({ top: 8, right: 10 })
  145.               .style({ strokeWidth: 10 })
  146.           }
  147.           if (this.showUrl === this.downloadUrl) {
  148.             Text('下载进度')
  149.             Progress({ value: this.downloadProgress, type: ProgressType.Linear })
  150.               .color('#009BE8').width('100%')
  151.               .margin({ top: 8, right: 10 })
  152.               .style({ strokeWidth: 10 })
  153.           }
  154.           // 展示请求内容
  155.           Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, }) {
  156.             Text("响应时间: " + (this.endTime - this.startTime) + "毫秒")
  157.               .width('100%')
  158.               .fontSize(16)
  159.               .fontWeight(700)
  160.               .fontColor('#000000')
  161.             Text("状态: " + this.status)
  162.               .width('100%')
  163.               .fontSize(16)
  164.               .fontWeight(700)
  165.               .fontColor('#000000')
  166.             Text("数据: " + this.message)
  167.               .width('100%')
  168.               .fontSize(16)
  169.               .fontWeight(700)
  170.               .fontColor('#000000')
  171.           }
  172.           .width('100%')
  173.           .padding({
  174.             top: 20,
  175.             bottom: 20,
  176.             right: 15,
  177.             left: 10
  178.           })
  179.           .margin({ right: 10 })
  180.           .borderStyle(BorderStyle.Solid)
  181.           .borderWidth(1)
  182.           .borderColor('#E6E7E8')
  183.         }
  184.         .margin({ top: 10, bottom: 20 })
  185.         .alignItems(HorizontalAlign.Start)
  186.         Button('清空')
  187.           .width(100).type(ButtonType.Normal)
  188.           .borderRadius(10)
  189.           .backgroundColor(Color.Green)
  190.           .onClick((e) => {
  191.           this.clear()
  192.         })
  193.       }
  194.     }
  195.     .scrollable(ScrollDirection.Vertical) // 滚动方向纵向
  196.     .scrollBar(BarState.On) // 滚动条常驻显示
  197.     .margin({ left: 10, right: 10 })
  198.   }
  199.   // Create请求: 使用get
  200.   create() {
  201.     this.clear()
  202.     this.showUrl = this.getUrl
  203.     const instance = axios.create();
  204.     this.startTime = new Date().getTime();
  205.     instance.get<string, AxiosResponse<string>, null>(this.getUrl, {
  206.     }).then((res: AxiosResponse) => {
  207.       this.status = res ? res.status : '';
  208.       this.message = res ? JSON.stringify(res.data) : '';
  209.       this.endTime = new Date().getTime();
  210.     }).catch((err: AxiosError) => {
  211.       this.status = '';
  212.       this.message = err.message;
  213.       this.endTime = new Date().getTime();
  214.     })
  215.   }
  216.   // request请求
  217.   request() {
  218.     this.clear()
  219.     this.showUrl = this.getUrl;
  220.     this.startTime = new Date().getTime();
  221.     axios.request<InfoModel, AxiosResponse<InfoModel>, IdModel>({
  222.       url: this.getUrl,
  223.       method: 'get',
  224.     }).then((res: AxiosResponse<InfoModel>) => {
  225.       this.status = res ? res.status : '';
  226.       this.message = res ? JSON.stringify(res.data) : '';
  227.       this.endTime = new Date().getTime();
  228.     }).catch((err: AxiosError) => {
  229.       this.status = '';
  230.       this.message = err.message;
  231.       this.endTime = new Date().getTime();
  232.     })
  233.   }
  234.   // get请求
  235.   get() {
  236.     this.clear()
  237.     this.showUrl = this.getUrl
  238.     this.startTime = new Date().getTime();
  239.     axios.get<string, AxiosResponse<string>, null>(this.getUrl, {
  240.     }).then((res: AxiosResponse) => {
  241.       this.status = res ? res.status : '';
  242.       this.message = res ? JSON.stringify(res.data) : '';
  243.       this.endTime = new Date().getTime();
  244.     }).catch((err: AxiosError) => {
  245.       this.status = '';
  246.       this.message = err.message;
  247.       this.endTime = new Date().getTime();
  248.     })
  249.   }
  250.   // post请求
  251.   post() {
  252.     this.clear()
  253.     this.showUrl = this.postUrl
  254.     this.startTime = new Date().getTime();
  255.     axios<InfoModel, AxiosResponse<InfoModel>, IdModel>({
  256.       url: this.postUrl,
  257.       method: 'post',
  258.       data: {
  259.         id: 591
  260.       },
  261.     }).then((res: AxiosResponse<InfoModel>) => {
  262.       this.status = res ? res.status : '';
  263.       this.message = res ? JSON.stringify(res.data) : '';
  264.       this.endTime = new Date().getTime();
  265.     }).catch((err: AxiosError) => {
  266.       this.status = '';
  267.       this.message = err.message;
  268.       this.endTime = new Date().getTime();
  269.     })
  270.   }
  271.   // put请求
  272.   put() {
  273.     this.clear()
  274.     this.showUrl = this.putUrl;
  275.     this.startTime = new Date().getTime();
  276.     axios.put<string, AxiosResponse<string>, IdModel>(this.putUrl, { id: 590 }, {
  277.     }).then((res: AxiosResponse) => {
  278.       this.status = res ? res.status : '';
  279.       this.message = res ? JSON.stringify(res.data) : '';
  280.       this.endTime = new Date().getTime();
  281.     }).catch((err: AxiosError) => {
  282.       this.status = '';
  283.       this.message = err.message;
  284.       this.endTime = new Date().getTime();
  285.     })
  286.   }
  287.   // delete请求
  288.   delete() {
  289.     this.clear()
  290.     this.showUrl = this.deleteUrl;
  291.     this.startTime = new Date().getTime();
  292.     axios.delete<string, AxiosResponse<string>, IdModel>(this.deleteUrl, {
  293.       data: {
  294.         id: 591
  295.       }
  296.     }).then((res: AxiosResponse) => {
  297.       this.status = res ? res.status : '';
  298.       this.message = res ? JSON.stringify(res.data) : '';
  299.       this.endTime = new Date().getTime();
  300.     }).catch((err: AxiosError) => {
  301.       this.status = '';
  302.       this.message = err.message;
  303.       this.endTime = new Date().getTime();
  304.     })
  305.   }
  306.   // 拦截器
  307.   interceptors() {
  308.     this.clear()
  309.     this.showUrl = this.getUrl
  310.     this.startTime = new Date().getTime();
  311.     const myInterceptor = axios.interceptors.response.use((response: AxiosResponse) => {
  312.       // 对响应数据做点什么
  313.       response.data = '在拦截器中,内容被更改了'
  314.       return response;
  315.     }, (error: AxiosError) => {
  316.       // 对响应错误做点什么
  317.       return Promise.reject(error);
  318.     });
  319.     axios<InfoModel[], AxiosResponse<InfoModel[]>, null>({
  320.       url: this.getUrl,
  321.       method: 'get',
  322.     }).then((res: AxiosResponse<InfoModel[]>) => {
  323.       this.status = res ? res.status : '';
  324.       this.message = res ? JSON.stringify(res.data) : '';
  325.       // 移除拦截器
  326.       axios.interceptors.response.eject(myInterceptor);
  327.       this.endTime = new Date().getTime();
  328.     }).catch((err: AxiosError) => {
  329.       this.status = '';
  330.       this.message = err.message;
  331.       // 移除拦截器
  332.       axios.interceptors.response.eject(myInterceptor);
  333.       this.endTime = new Date().getTime();
  334.     })
  335.   }
  336.   // 默认设置
  337.   defaultSetting() {
  338.     this.clear()
  339.     this.showUrl = this.postUrl
  340.     this.startTime = new Date().getTime();
  341.     axios.defaults.headers['customer-header'] = 'customer-value'
  342.     axios.defaults.method = 'post'
  343.     axios<InfoModel, AxiosResponse<InfoModel>, IdModel>({
  344.       url: this.postUrl,
  345.       data: {
  346.         id: 590
  347.       },
  348.       // connectTimeout: this.connectTimeout,
  349.       // readTimeout: this.readTimeout,
  350.       // maxBodyLength: this.maxBodyLength,
  351.       // maxContentLength: this.maxContentLength
  352.     }).then((res: AxiosResponse<InfoModel>) => {
  353.       this.status = res.status;
  354.       this.message = JSON.stringify(res.data);
  355.       axios.defaults.method = '';
  356.       axios.defaults.headers['customer-header'] = null;
  357.       this.endTime = new Date().getTime();
  358.     }).catch((err: AxiosError) => {
  359.       this.status = '';
  360.       this.message = err.message;
  361.       axios.defaults.method = '';
  362.       axios.defaults.headers['customer-header'] = null
  363.       this.endTime = new Date().getTime();
  364.     })
  365.   }
  366.   // 下载
  367.   download() {
  368.     this.clear()
  369.     this.showUrl = this.downloadUrl
  370.     this.startTime = new Date().getTime();
  371.     // let filePath = getContext(this).cacheDir + '/blue.jpg'
  372.     let filePath = getContext(this).cacheDir + '/qq.exe'
  373.     // 下载。如果文件已存在,则先删除文件。
  374.     try {
  375.       fs.accessSync(filePath);
  376.       fs.unlinkSync(filePath);
  377.     } catch (err) {
  378.     }
  379.     axios<string, AxiosResponse<string>, null>({
  380.       url: this.downloadUrl,
  381.       method: 'get',
  382.       context: getContext(this),
  383.       filePath: filePath,
  384.       onDownloadProgress: (progressEvent: AxiosProgressEvent): void => {
  385.         this.downloadProgress = progressEvent && progressEvent.loaded && progressEvent.total ?
  386.         Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0;
  387.       }
  388.     }).then((res: AxiosResponse<string>) => {
  389.       this.status = res ? res.status : '';
  390.       this.message = res ? JSON.stringify(res.data) : '';
  391.       this.endTime = new Date().getTime();
  392.     }).catch((err: AxiosError) => {
  393.       this.status = '下载失败!';
  394.       this.message = err.message;
  395.       this.endTime = new Date().getTime();
  396.     })
  397.   }
  398.   // 上传
  399.   upload() {
  400.     this.clear()
  401.     this.showUrl = this.uploadUrl
  402.     this.startTime = new Date().getTime();
  403.     let context: Context = getContext(this);
  404.     // let fileBuf: Uint8Array = context.resourceManager.getRawFileContentSync("oneWayAuth/fileBuf.pem");
  405.     let fileBuf: Uint8Array = context.resourceManager.getRawFileContentSync("readme.txt");
  406.     let cacheDir: string = context.cacheDir;
  407.     let buffer: ArrayBuffer = new ArrayBuffer(1024);
  408.     try {
  409.       writeFile(cacheDir, 'readme.txt', fileBuf.buffer);
  410.       // 读取
  411.       buffer = readFile(cacheDir + '/readme.txt');
  412.     } catch (err) {
  413.       console.error(TAG, JSON.stringify(err))
  414.     }
  415.     let formData = new FormData();
  416.     formData.append('file', buffer, { filename: 'readme.txt', type: 'text/plain' });
  417.     axios.post<UploadModel, AxiosResponse<UploadModel>, FormData>(this.uploadUrl, formData, {
  418.       headers: { 'Content-Type': 'multipart/form-data' },
  419.       context: getContext(this),
  420.       onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
  421.         console.info(TAG, JSON.stringify(progressEvent))
  422.         this.uploadProgress = progressEvent && progressEvent.loaded && progressEvent.total ?
  423.         Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0;
  424.       },
  425.     }).then((res: AxiosResponse<UploadModel>) => {
  426.       this.status = res ? res.status : '';
  427.       this.message = res ? JSON.stringify(res.data) : '';
  428.       console.info(TAG, JSON.stringify(res.headers));
  429.       this.endTime = new Date().getTime();
  430.     }).catch((err: AxiosError) => {
  431.       this.status = '';
  432.       this.message = err.message;
  433.       this.endTime = new Date().getTime();
  434.     })
  435.   }
  436.   // 设置双向证书校验(无密码)
  437.   settingClientCert() {
  438.     this.clear()
  439.     this.showUrl = this.clientCert_noPsw
  440.     this.startTime = new Date().getTime();
  441.     let path_ca = ''; // 根证书路径
  442.     let path_client = ''; // 客户端证书路径
  443.     let path_key = ''; // 客户端密码路径
  444.     // 获取根证书、客户端证书、客户端密码沙箱路径
  445.     try {
  446.       let context: Context = getContext(this);
  447.       let ca: Uint8Array = context.resourceManager.getRawFileContentSync("oneWayAuth/ca.p12");
  448.       let client: Uint8Array = context.resourceManager.getRawFileContentSync("mutualAuth_noPsw/p12/client.p12");
  449.       let key: Uint8Array = context.resourceManager.getRawFileContentSync("mutualAuth_noPsw/p12/client.key");
  450.       let cacheDir: string = context.cacheDir;
  451.       if (ca != null) {
  452.         path_ca = cacheDir + "/ca.crt";
  453.         writeFile(cacheDir, 'ca.crt', ca.buffer)
  454.       }
  455.       if (client != null) {
  456.         path_client = cacheDir + "/client.p12";
  457.         writeFile(cacheDir, 'client.p12', client.buffer)
  458.       }
  459.       if (key != null) {
  460.         path_key = cacheDir + "/client.key";
  461.         writeFile(cacheDir, 'client.key', key.buffer)
  462.       }
  463.     } catch (err) {
  464.       console.info(TAG, JSON.stringify(err));
  465.     }
  466.     axios<InfoModel, AxiosResponse<InfoModel>, null>({
  467.       url: this.clientCert_noPsw,
  468.       method: 'get',
  469.       caPath: path_ca,
  470.       clientCert: {
  471.         certPath: path_client,
  472.         certType: 'p12',
  473.         keyPath: path_key,
  474.       },
  475.     }).then((res: AxiosResponse<InfoModel>) => {
  476.       this.status = res ? res.status : '';
  477.       this.message = res ? JSON.stringify(res.data) : '';
  478.       this.endTime = new Date().getTime();
  479.     }).catch((err: AxiosError) => {
  480.       this.status = '';
  481.       this.message = err.message;
  482.       this.endTime = new Date().getTime();
  483.     })
  484.   }
  485.   // 设置双向证书校验(有密码)
  486.   settingClientCert_psw() {
  487.     this.clear()
  488.     this.showUrl = this.clientCert_hasPsw
  489.     this.startTime = new Date().getTime();
  490.     let path_ca = ''; // 根证书路径
  491.     let path_client = ''; // 客户端证书路径
  492.     let path_key = ''; // 客户端密码路径
  493.     // 获取根证书、客户端证书、客户端密码沙箱路径
  494.     try {
  495.       let context: Context = getContext(this);
  496.       let ca: Uint8Array = context.resourceManager.getRawFileContentSync("mutualAuth_hasPsw/ca.crt");
  497.       let client: Uint8Array = context.resourceManager.getRawFileContentSync("mutualAuth_hasPsw/pem/client.pem");
  498.       let key: Uint8Array = context.resourceManager.getRawFileContentSync("mutualAuth_hasPsw/pem/client.key");
  499.       let cacheDir: string = context.cacheDir;
  500.       if (ca != null) {
  501.         path_ca = cacheDir + "/ca.crt";
  502.         writeFile(cacheDir, 'ca.crt', ca.buffer)
  503.       }
  504.       if (client != null) {
  505.         path_client = cacheDir + "/client.pem";
  506.         writeFile(cacheDir, 'client.pem', client.buffer)
  507.       }
  508.       if (key != null) {
  509.         path_key = cacheDir + "/client.key";
  510.         writeFile(cacheDir, 'client.key', key.buffer)
  511.       }
  512.     } catch (err) {
  513.       console.info(TAG, JSON.stringify(err));
  514.     }
  515.     axios<InfoModel, AxiosResponse<InfoModel>, null>({
  516.       url: this.clientCert_hasPsw,
  517.       method: 'get',
  518.       caPath: path_ca,
  519.       clientCert: {
  520.         certPath: path_client,
  521.         certType: 'pem',
  522.         keyPath: path_key,
  523.         keyPasswd: this.psw
  524.       },
  525.     }).then((res: AxiosResponse<InfoModel>) => {
  526.       this.status = res ? res.status : '';
  527.       this.message = res ? JSON.stringify(res.data) : '';
  528.       this.endTime = new Date().getTime();
  529.     }).catch((err: AxiosError) => {
  530.       this.status = '';
  531.       this.message = err.message;
  532.       this.endTime = new Date().getTime();
  533.     })
  534.   }
  535.   // 设置响应类型
  536.   settingResponseType() {
  537.     this.clear()
  538.     this.showUrl = this.getUrl
  539.     this.startTime = new Date().getTime();
  540.     axios<string, AxiosResponse<string>, null>({
  541.       url: this.getUrl,
  542.       method: 'get',
  543.       responseType: 'array_buffer',
  544.     }).then((res: AxiosResponse) => {
  545.       this.status = res ? res.status : '';
  546.       if (res.data instanceof ArrayBuffer) {
  547.         this.message = res ? 'responseType设置成功' : '';
  548.       }
  549.       this.endTime = new Date().getTime();
  550.     }).catch((err: AxiosError) => {
  551.       this.status = '';
  552.       this.message = err.message;
  553.       this.endTime = new Date().getTime();
  554.     })
  555.   }
  556.   // 设置代理
  557.   settingProxy() {
  558.     this.clear()
  559.     this.showUrl = this.proxyUrl
  560.     this.startTime = new Date().getTime();
  561.     axios<string, AxiosResponse<string>, null>({
  562.       url: this.proxyUrl,
  563.       method: 'get',
  564.       proxy: {
  565.         host: this.host,
  566.         port: 6443,
  567.         exclusionList: []
  568.       },
  569.     }).then((res: AxiosResponse) => {
  570.       this.status = res ? res.status : '';
  571.       this.message = res ? JSON.stringify(res.data) : '';
  572.       this.endTime = new Date().getTime();
  573.     }).catch((err: AxiosError) => {
  574.       this.status = '';
  575.       this.message = err.message;
  576.       this.endTime = new Date().getTime();
  577.     })
  578.   }
  579.   clear() {
  580.     this.performanceTiming = '';
  581.     this.uploadProgress = 0;
  582.     this.downloadProgress = 0
  583.     this.message = '';
  584.     this.status = '';
  585.     this.startTime = 0;
  586.     this.endTime = 0;
  587.   }
  588. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

干翻全岛蛙蛙

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表