头图

需求:加载验证码;1.下载验证码图像文件;2.获取header里面验证码ID

踩坑--踩坑--踩坑

根据文档使用 request.downloadFile 请求,官方示例:

// pages/xxx.ets
// 将网络资源文件下载到应用文件目录并读取一段内容
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';

// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;

try {
  request.downloadFile(context, {
    url: 'https://xxxx/xxxx.txt',
    filePath: filesDir + '/xxxx.txt'
  }).then((downloadTask) => {
    downloadTask.on('complete', () => {
      console.info('download complete');
      let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
      let buf = new ArrayBuffer(1024);
      let readLen = fs.readSync(file.fd, buf);
      console.info(`The content of file: ${String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))}`);
      fs.closeSync(file);
    })
  }).catch((err) => {
    console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
  });
} catch (err) {
  console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
}复制

里面存在一个解决不到的问题是,获取不到header里面验证码ID,downloadTask 无法获取....只能换常规方法获取了。

换 httpRequest.request 来请求,示例代码如下:

  /**
   * 下载文件(验证码使用)
   */
  static httpFileDownload(url: string, params?: any): Promise<ResponseResultJson> {
    LogUtils.i("下载文件URL:" + url + "\n请求参数:" + (params != undefined ? "\n请求参数:" + JSON.stringify(params) : "无参数"));
    //
    let httpRequest = http.createHttp();
    httpRequest.on('headersReceive', (header) => {
      //用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
    });
    //
    let responseResult = httpRequest.request(url, {
      method: http.RequestMethod.GET,
      readTimeout: RequestConstants.readTimeout,
      connectTimeout: RequestConstants.connectTimeout,
      header: {
        'Content-Type': ContentType.JSON
      },
      expectDataType: http.HttpDataType.ARRAY_BUFFER, // 可选,指定返回数据的类型
      extraData: params
    });
    let responseResultJson = new ResponseResultJson();
    return responseResult.then(async (responseResult: http.HttpResponse) => {
      LogUtils.i("文件下载请求响应URL:" + url + "\n响应结果:" + "\n" + JSON.stringify(responseResult));
      if (responseResult.responseCode === ResponseConstants.RESPONSE_SUCCESS) {
        let header = responseResult.header
        LogUtils.i('解析响应 header \n' + JSON.stringify(header));
        let headerJson = JSON.stringify(header)
        let headerObj = JSON.parse(headerJson)
        let sessionId = headerObj.sessionid as string
        let serverModel = headerObj.servermodel as string
        let encryptType = headerObj.encrypttype as string
        //保存 header
        await AppHelper.commitSessionId(sessionId);
        await AppHelper.commitServerModel(serverModel);
        await AppHelper.commitEncryptType(encryptType);
        //解析文件
        let result = responseResult.result as ArrayBuffer
        // let filePath = FileConstants.rootFile + "/verifyCode_" + TimeExUtils.getNowYMDHMS1() + '.jpg'
        let isHave = fs.accessSync(FileConstants.pathFile) //检查文件目录是否存在
        if (!isHave) fs.mkdirSync(FileConstants.pathFile) //创建目录
        //
        let filePath = FileConstants.pathFile + "verifyCode_" + TimeExUtils.getNowYMDHMS1() + '.jpg'
        let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
        fs.writeSync(file.fd, result); //将数据写入文件
        fs.closeSync(file); //关闭文件
        //
        LogUtils.i("保存文件成功:\n" + filePath + "\t" + await FileUtils.getPathSize(filePath));
        //结果
        responseResultJson.code = ResponseConstants.CODE_SUCCESS
        responseResultJson.isSuccess = true
        responseResultJson.status = responseResult.responseCode
        responseResultJson.serverModel = serverModel
        responseResultJson.filePath = filePath
      } else {
        responseResultJson.code = ResponseConstants.CODE_ERROR;
        responseResultJson.message = "业务异常:" + JSON.stringify(responseResult)
        responseResultJson.isSuccess = false
      }
      return responseResultJson;
    }).catch((error) => {
      LogUtils.i("文件下载请求响应URL:" + url + "\n请求异常:\n" + JSON.stringify(error))
      responseResultJson.code = ResponseConstants.CODE_ERROR;
      responseResultJson.message = "请求异常:\n" + JSON.stringify(error)
      responseResultJson.isSuccess = false
      return responseResultJson;
    });
  }复制

里面无用工具类可以不用在意...里面获取header可以有2种方法

鸿蒙OS开发更多内容↓点击HarmonyOS与OpenHarmony技术
鸿蒙技术文档开发知识更新库gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md在这。或+mau123789学习,是v喔

方法一:

搜狗高速浏览器截图20240326151547.png

资料拿取+mau123789是v喔
 httpRequest.on('headersReceive', (header) => {
      //用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
    });

方法二:

let header = responseResult.header
        LogUtils.i('解析响应 header \n' + JSON.stringify(header));
        let headerJson = JSON.stringify(header)
        let headerObj = JSON.parse(headerJson)
        let sessionId = headerObj.sessionid as string
        let serverModel = headerObj.servermodel as string
        let encryptType = headerObj.encrypttype as string

获取的值是一样的。

获取验证码文件关键代码:

1.参数里面的 expectDataType 需要设置为 http.HttpDataType.ARRAY_BUFFER;

  1. 结果转换为ArrayBuffer,let result = responseResult.result as ArrayBuffer

运行日志:

cke_2126.png

运行效果:

cke_6226.png

完毕啦!!!! 验证码获取成功了!!!!


烧脑猴
24 声望21 粉丝

5年JAVA,3年Android。现转入鸿蒙开发行业,每日分享一些鸿蒙技术!