HarmonyOS鸿蒙Next中ssl error request.agent能绕过验证吗,我又采用了rcp可以绕过需要配置header还要传data给我提供一个下载文件demo

HarmonyOS鸿蒙Next中ssl error request.agent能绕过验证吗,我又采用了rcp可以绕过需要配置header还要传data给我提供一个下载文件demo

4 回复

可以看下这个

import rcp from '@hms.collaboration.rcp';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
import { JSON } from '@kit.ArkTS';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
  @State transValue: number = 0
  @State totalData: number = 0
  @State progress: number = 0
  arrData = new ArrayBuffer(0)
  downloadUrl: string ='真实的下载地址';
  context = getContext(this) as common.UIAbilityContext
  filePath = `${this.context.filesDir}/test.png`

  build() {
    Column() {
      Row() {
        Button('下载文件')
          .onClick(() => {
            this.transValue = 0
            this.progress = 0

            // 下载文件数据
            this.getDownloadTotalSize(this.downloadUrl)
            this.getDownloadProgress(this.downloadUrl)
          })
      }
      Row() {
        Progress({ value: 0, total: 100, type: ProgressType.Capsule }).width(200).height(50).value(this.progress)
        Text(this.progress.toFixed(2) + '%')
      }
    }
    .height('100%')
    .width('100%')
  }

  // head请求获取数据总大小
  getDownloadTotalSize(url: string) {

    // 请求获取文件大小
    const session = rcp.createSession();
    session.head(url).then((response) => {
      this.arrData = new ArrayBuffer(this.totalData)

      // 获取文件总大小
      this.totalData = Number(JSON.stringify(response.headers, ['content-length']).split(':"')[1].split('"}')[0])
      let file = fs.openSync(this.filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      fs.fsyncSync(file.fd);
      fs.closeSync(file);
      session.close()
    }).catch((err: BusinessError) => {
      console.error(`err: err code is ${err.code}`)
      session.close()
    });
  }

  // 下载文件监听进度
  getDownloadProgress(url: string) {

    // 响应数据处理
    const customHttpEventsHandler: rcp.HttpEventsHandler = {

      // 下载数据监听
      onDownloadProgress: (totalSize: number, transferredSize: number) => {
        this.transValue = transferredSize
        this.progress = this.transValue / this.totalData * 100
        console.info("Download progress:", transferredSize, "of", totalSize);
      },

      // 数据完成接收监听
      onDataEnd: () => {
        console.info("Data transfer complete");
      },

      // 取消数据接收监听
      onCanceled: () => {
        console.info("Request/response canceled");
      },
    };

    // TracingConfiguration用于获取请求期间详细信息
    const tracingConfig: rcp.TracingConfiguration = {
      verbose: true,
      collectTimeInfo: true,
      httpEventsHandler: customHttpEventsHandler,
    };

    // 建立session对象
    let session = rcp.createSession({
      // 指定与会话关联的HTTP请求的配置
      requestConfiguration: {
        tracing: tracingConfig,
        dns: {
          dnsOverHttps: {
            url: '请求地址',
            skipCertificatesValidation: true
          }
        }
      }
    });
    // 下载文件
    session.downloadToFile(url, {
      kind: 'file',
      file: `${this.context.filesDir}/img.png`,
    }).then((response) => {
      console.info(`Down result ${response.toJSON()}`)
      session.close();
    }).catch((err: Error) => {
      session.close();
    });
  }
}

更多关于HarmonyOS鸿蒙Next中ssl error request.agent能绕过验证吗,我又采用了rcp可以绕过需要配置header还要传data给我提供一个下载文件demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


request.agent默认不支持跳过SSL校验,楼主可以试试配置SecurityConfiguration的remoteValidation参数为skip:

import { rcp } from '@kit.RemoteCommunicationKit';

// 创建请求配置

let securityConfig: rcp.SecurityConfiguration = {

  remoteValidation: 'skip' // 跳过SSL校验

};

let req = new rcp.Request('https://example.com/file.zip');

req.securityConfiguration = securityConfig;

文件下载Demo:

import { common } from '@kit.AbilityKit';

import { rcp } from '@kit.RemoteCommunicationKit';

import { BusinessError } from '@kit.BasicServicesKit';

@Entry

@Component

struct DownloadDemo {

  build() {

    Button('下载文件')

      .onClick(() => {

        let context = this.getUIContext().getHostContext() as common.UIAbilityContext;

        let downloadPath = context.filesDir + '/download_file.zip'; // 保存路径

        // 配置请求

        let req = new rcp.Request('https://example.com/file.zip');

        req.method = 'GET';

        req.headers = { 'Authorization': 'Bearer your_token_here' }; // 设置Token

        // 跳过SSL校验

        let securityConfig: rcp.SecurityConfiguration = {

          remoteValidation: 'skip'

        };

        req.securityConfiguration = securityConfig;

        // 下载到文件配置

        let downloadConfig: rcp.DownloadToFile = {

          kind: 'file',

          path: downloadPath

        };

        // 发送请求

        rcp.session.fetch(req, { downloadToFile: downloadConfig })

          .then((resp: rcp.Response) => {

            if (resp.code === 200) {

              console.info('下载成功,路径:' + downloadPath);

            }

          })

          .catch((err: BusinessError) => {

            console.error(`下载失败,错误码:${err.code},信息:${err.message}`);

          });

      })

  }

}

在HarmonyOS Next中,ssl error通常需要正确配置SSL证书验证,不能直接绕过。使用request.agent时,确保服务器证书有效且受信任。若采用RCP方式,需在请求头中配置Content-Type等字段,并通过data参数传递必要信息。下载文件可使用@ohos.net.http模块,示例代码:

import http from '@ohos.net.http';
let request = http.createHttp();
request.request('https://example.com/file', {
  method: 'GET',
  header: { 'Content-Type': 'application/octet-stream' }
}, (err, data) => {
  if (!err) {
    // 处理文件数据
  }
});

在HarmonyOS Next中,request.agent 默认不支持绕过SSL验证。如果使用RPC(如通过@ohos.net.http模块),可以通过配置skipCertificateValidation跳过证书验证,但需注意安全风险。同时,需在header中传递token,并在data中提供必要参数。

以下是一个基于@ohos.net.http的下载文件示例代码:

import http from '@ohos.net.http';

let token = 'YOUR_TOKEN'; // 替换为实际token
let url = 'https://example.com/file.zip'; // 替换为实际下载URL

let request = http.createHttp();
let headers = {
  'Content-Type': 'application/json',
  'token': token
};
let data = {
  // 根据接口要求传递参数,例如文件ID或路径
  fileId: '123'
};

request.request(
  url,
  {
    method: http.RequestMethod.POST, // 或GET,根据接口调整
    header: headers,
    extraData: JSON.stringify(data),
    connectTimeout: 60000,
    readTimeout: 60000,
    usingProtocol: http.HttpProtocol.HTTP1_1,
    skipCertificateValidation: true // 跳过SSL验证
  }, (err, data) => {
    if (err) {
      console.error('Download failed: ' + JSON.stringify(err));
      return;
    }
    if (data.responseCode === 200) {
      // 处理文件数据,例如保存到本地
      let fileData = data.result;
      // 此处需调用文件系统API(如@ohos.file.fs)写入文件
      console.info('Download successful');
    } else {
      console.error('Server error: ' + data.responseCode);
    }
  }
);

注意事项:

  1. 跳过SSL验证(skipCertificateValidation: true)仅用于测试环境,生产环境应使用有效证书。
  2. 实际参数(如data中的字段)需根据后端接口调整。
  3. 文件保存需使用@ohos.file.fs模块实现写入操作。

如果需要更完整的文件保存逻辑,请参考HarmonyOS文件管理API文档。

回到顶部