详细介绍:【FAQ】HarmonyOS SDK 闭源开放能力 — Network Kit

1.问题描述:

在系统网络代理在被清除后,鸿蒙web组件尝试打开网页时,获取到了系统网络代理,导致网页打开失败。

解决方案:

  1. 检查网络权限配置 确保在 module.json5 配置文件中已声明必要的网络权限:
"requestPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  },
  {
    "name": "ohos.permission.GET_NETWORK_INFO"
  }
]

缺少权限可能导致网络请求被系统拦截。

  1. 调整Web组件属性 在Web组件中添加以下关键属性以增强网络访问能力:
Web({
  src: 'https://example.com'
})
.domStorageAccess(true)  // 启用DOM存储
.fileAccess(true)        // 允许文件访问
.javaScriptAccess(true)  // 启用JavaScript

部分网页功能(如WebSocket)需要开启特定权限。

  1. 处理代理残留问题

清除缓存:手动清除应用缓存或重启应用,避免代理配置残留。

设置自定义UserAgent:部分网络问题可通过覆盖默认UserAgent解决:

Web({
  src: 'https://example.com'
})
.userAgent('Mozilla/5.0 HarmonyOS-WebView')
  1. 服务端兼容性验证

若涉及跨域请求(如开发环境调用远程API),需服务端配置CORS响应头(如 Access-Control-Allow-Origin: *)。

通过Postman等工具直接测试接口,排除服务端问题。

  1. SDK版本与网络配置

确保使用最新版SDK,旧版本可能存在网络组件兼容性问题。

检查系统全局代理设置是否完全关闭(路径:系统设置 > 网络和互联网 > 代理)。

若问题仅在Web组件中复现,而系统浏览器正常,需重点排查组件属性配置及权限声明。开发过程中可通过DevTools日志(FocusedHitDataChange 类错误)定位具体失败环节。

2.问题描述:

目前有的流量管理模块https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/net-statistics里面的api,要么是统计整个设备的,要么是统计某个应用总的,有什么办法分开统计某一个应用的蜂窝和Wi-Fi吗?

解决方案:

【解决方案】

固定时间分别获取网卡和蜂窝实时上行和下行流量,两个数值的差额即为每天设备的流量统计。

部分代码示例:

TypeScript
import { statistics, socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
  @State message: string = 'Statistics';
  getIfaceBytes() {
    // 获取指定网卡实时下行流量
    statistics.getIfaceRxBytes("wlan0").then((stats: number) => {
      console.log(`wlan0 down size = ${stats}`);
    });
    // 获取指定网卡实时上行流量
    statistics.getIfaceTxBytes("wlan0").then((stats: number) => {
      console.log(`wlan0 up size = ${stats}`);
    });
  }
  getCellularBytes() {
    // 获取蜂窝实时下行流量
    statistics.getCellularRxBytes((error: BusinessError, stats: number) => {
      if (error) {
        console.error(`getCellularRxBytes err, code: ${error.code}, message: ${error.message}`);
        return;
      }
      console.log(`cellular down size = ${stats}`);
    });
    // 获取蜂窝实时上行流量
    statistics.getCellularTxBytes((error: BusinessError, stats: number) => {
      if (error) {
        console.error(`getCellularTxBytes err, code: ${error.code}, message: ${error.message}`);
        return;
      }
      console.log(`cellular up size = ${stats}`);
    });
  }
  build() {
    RelativeContainer() {
      Text(this.message)
        .id('Statistics')
        .fontSize($r('app.float.page_text_font_size'))
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          this.message = 'Welcome';
          this.getIfaceBytes();
          this.getCellularBytes()
        })
    }
    .height('100%')
    .width('100%')
  }
}

3.问题描述:

调用getCellularRxBytes/getCellularTxBytes接口异常,{"code":2103012,"message":"Get iface name failed"},如何解决?

解决方案:

在使用Wi-Fi场景下,调用getCellularTxBytes会出现上述异常,切换到蜂窝流量调用即可。

4.问题描述:

手动连接无网Wi-Fi,不会弹“当前WLAN不可上网,是否继续使用此WLAN”弹窗。

解决方案:

弹框只在首次连接弹出,不会重复弹出。将热点删除后重新连接,弹框会再次弹出。

5.问题描述:

系统打开VPN导致ohso.request下载接口失败,其它RCP接口请求可以正常使用。

解决方案:

上传下载是在独立的SA进程,所以走VPN的应用不能使用ohso.request接口,RCP是在应用进程传输数据。

6.问题描述:

创建VPN时Config配置中网关地址与VPN IP地址是否可以不一致?

解决方案:

网关地址与VPN分配的IP地址不在同一网段,会出现路由失效的情况,设备无法通过默认网关转发数据,导致连接超时或无法访问目标网络。应保证网关地址和VPN IP地址在同一网段,或将网关地址置空。

7.问题描述:

调试报错码2300023,Failed to write the received data to the disk/application.这个异常是接口超5M限制了吗?有什么解决方案?

解决方案:

因为http请求中下载文件超过5M的阈值导致图片过大而报错,http发起请求的响应消息的最大字节限制默认值是510241024,设置响应数据最大字节限制为100M或是采用流式传输。

【修改建议】

  • 方案一:maxLimit修改为100M。
http.createHttp().request(url,
      {
        method: http.RequestMethod.GET,
        connectTimeout: 60000,
        readTimeout: 60000,
        maxLimit: 100 * 1024 * 1024,
      },
  • 方案二:采用流式传输。
// 在dataReceive中拼接图片数据
let imageChunks: ArrayBuffer[] = [];
httpRequest.on('dataReceive', (data: ArrayBuffer) => {
  imageChunks.push(data);
  console.info('收到分片,大小:' + data.byteLength + ' bytes');
});
httpRequest.on('dataEnd', () => {
  // 计算总长度
  let totalLength = imageChunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
  let fullImage = new Uint8Array(totalLength);
  // 拼接所有分片数据
  let offset = 0;
  for (let chunk of imageChunks) {
    fullImage.set(new Uint8Array(chunk), offset);
    offset += chunk.byteLength;
  }
  console.info('图片接收完成,总大小:' + totalLength + 'bytes');
  const base64 = btoa(String.fromCharCode(...fullImage));
  const imgSrc = `data:image/png;base64,${base64}`;
  console.info('可用于展示的图片 src:', imgSrc);
});
posted @ 2025-12-09 14:54  gccbuaa  阅读(1)  评论(0)    收藏  举报