HarmonyOS 鸿蒙Next @ohos.request (https+ip 有问题,但报错failCode太误导人了)

HarmonyOS 鸿蒙Next @ohos.request (https+ip 有问题,但报错failCode太误导人了)

this.downloadTask = await request.downloadFile(getContext(), {
    url: this.url,
    filePath: PDFFilePath
})
this.downloadTask.on('fail', (err: number) => {
    this.handleDownloadFail(err, PDFFilePath);
})
private handleDownloadFail(errCode: number, url: string) {
    console.info(`PDF download fail errCode: ${errCode} url: ${url}`);
    //download fail errCode: 2 url: https://117.157.68.156:6443/.well-known/zhbxxgs.pdf?encode=utf-8
}

1、 坑爹官方提供的下载任务的错误码

@[@ohos](/user/ohos).request (上传下载)
名成 参数类型 数值 说明
ERROR_FILE_ALREADY_EXISTS7+ number 2 要下载的文件已存在,下载会话不能覆盖现有文件。

2、 解决方式(https+ip 有问题,但报错code太误导人了)


更多关于HarmonyOS 鸿蒙Next @ohos.request (https+ip 有问题,但报错failCode太误导人了)的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复
  1. 第一个问题,文件已存在可以通过以下代码进行规避
//下载前判断文件是否存在, 如果存在就删除
let res = fs.accessSync(filePath);
if (res) {
  fs.unlinkSync(filePath);
}
  1. 第二个问题,本地部署服务器地址下载失败报errCode=2的问题内部处理中,请耐心等待

一开始尝试添加UA来尝试发现仍然失败,可能我这边是外部访问的缘故把,您可以尝试添加以下代码看看是否解决

request.downloadFile(context, {
  url: 'https://117.157.68.156:6443/.well-known/zhbxxgs.pdf?encode=utf-8',
  // url: 'https://zhbbasesit.hlzq.com:6443/.well-known/zhbxxgs.pdf?encode=utf-8',
  filePath: filePath,
  header: {
    "User-Agent": "Opera/9.60 (Windows NT 6.0; U; en) Presto/2.1.1"
  }
})

以下是我的完整复现demo:

import common from '@ohos.app.ability.common';
import fs, { ReadOptions, WriteOptions } from '@ohos.file.fs';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { buffer } from '@kit.ArkTS';

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

@Component
export struct downloadHttpPdf {
  @State message: string = '1.下载图片';

  build() {
    Column({ space: 20 }) {
      Button(this.message)
        .id('SaveDemo')
        .fontSize(16)
        .fontWeight(FontWeight.Bold)
        .onClick(() => {
          this.downLoad();
        });
    }
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
    .height('100%')
    .width('100%');
  }

  downLoad() {
    let filePath = cacheDir + '/a.pdf'
    try {
      //下载前判断文件是否存在, 如果存在就删除
      let res = fs.accessSync(filePath);
      if (res) {
        fs.unlinkSync(filePath);
      }
      request.downloadFile(context, {
        url: 'https://117.157.68.156:6443/.well-known/zhbxxgs.pdf?encode=utf-8',
        // url: 'https://zhbbasesit.hlzq.com:6443/.well-known/zhbxxgs.pdf?encode=utf-8',
        filePath: filePath,
        header: {
          "User-Agent": "Opera/9.60 (Windows NT 6.0; U; en) Presto/2.1.1"
        }
      }).then((downloadTask: request.DownloadTask) => {
        try {
          downloadTask.on('complete', () => {
            console.info('download complete');
            // 如果不是网络下载图片,就只用下面的代码,读取本地沙箱路径
            let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
            let arrayBuffer = new ArrayBuffer(1024);
            let readLen = fs.readSync(file.fd, arrayBuffer);
            let buf = buffer.from(arrayBuffer, 0, readLen);
            console.info(`The content of file: ${buf.toString()}`);
            fs.closeSync(file);
          });
          downloadTask.on('fail', (err: number) => {
            console.error(`Invoke downloadFile failed, code is ${err}, message is ${err}`);
          })
        } catch (error) {
          let err: BusinessError = error as BusinessError;
          console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
        }
      }).catch((err: BusinessError) => {
        console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
    }
  }

  copyFile(srcFile: fs.File, destFile: fs.File) {
    // 读取源文件内容并写入至目的文件
    let bufSize = 4096;
    let readSize = 0;
    let buf = new ArrayBuffer(bufSize);

    let readOptions: ReadOptions = {
      offset: readSize,
      length: bufSize
    };

    let readLen = fs.readSync(srcFile.fd, buf, readOptions);
    while (readLen > 0) {
      readSize += readLen;
      let writeOptions: WriteOptions = {
        length: readLen
      };
      fs.writeSync(destFile.fd, buf, writeOptions);
      readOptions.offset = readSize;
      readLen = fs.readSync(srcFile.fd, buf, readOptions);
    }

    // 关闭文件
    fs.closeSync(srcFile);
    fs.closeSync(destFile);
  }
}

更多关于HarmonyOS 鸿蒙Next @ohos.request (https+ip 有问题,但报错failCode太误导人了)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


针对您提到的HarmonyOS 鸿蒙Next中的@ohos.request在使用HTTPS+IP时遇到问题,并且报错failCode具有误导性的情况,以下是一些直接相关的可能原因和解决方案概述:

  1. 证书问题:确保服务器端的SSL/TLS证书有效且未被吊销,同时证书链完整。鸿蒙系统对证书验证较为严格,任何证书错误都可能导致请求失败。

  2. IP地址访问限制:某些服务器配置可能不允许直接通过IP地址进行HTTPS访问,需要通过域名访问。检查服务器配置,确保支持IP访问或改用域名。

  3. 端口配置:确认服务器HTTPS服务监听的端口正确无误,且防火墙或网络策略允许该端口的流量通过。

  4. 协议版本或加密算法不兼容:检查客户端(鸿蒙设备)与服务器之间的TLS协议版本和加密算法是否兼容。老旧或不安全的算法可能不被支持。

  5. failCode具体含义:查阅鸿蒙系统的官方文档或错误代码库,了解特定failCode的详细含义,以便更准确地定位问题。

如果问题依旧没法解决请联系官网客服,官网地址是:官网地址

回到顶部