HarmonyOS 鸿蒙Next中如何下载JSON字符串

HarmonyOS 鸿蒙Next中如何下载JSON字符串 项目中需要下载JSON文件到本地,然后使用首选项存储,目前下载JSON文件遇到了困难,帮忙封装一个下载的工具类,感谢!

具体需求如下:

  1. 下载地址: https://app-demo.iandun.com/settings.json?v=1718157761736 其中 V 后面的是一个当前时间戳
  2. 封装一个下载工具类,把上面链接获取的JSON字符串用首选项存储在手机中。
3 回复

demo参考如下: 首选项一次存不下这么多内容,我们进行了分段存储的处理

import { BusinessError } from '@kit.BasicServicesKit';
import common from '@ohos.app.ability.common';
import fs, { Options } from '@ohos.file.fs';
import request from '@ohos.request';
import buffer from '@ohos.buffer';
import dataPreferences from '@ohos.data.preferences';

@Entry
@Component
struct Test {
  @State message: string = 'aaaaa';
  context = this.context as common.UIAbilityContext
  filesDir = this.context.filesDir
  preferences: dataPreferences.Preferences | null = null;

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let filePath = getContext().filesDir + '/helloworld.txt'
            fs.unlink(filePath).then(() => {
              console.info("remove file succeed");
            }).catch((err: BusinessError) => {
              console.error("remove file failed with error message: " + err.message + ", error code: " + err.code);
            });

            let filePath1 = getContext().filesDir + '/new.txt'
            fs.unlink(filePath1).then(() => {
              console.info("remove file succeed");
            }).catch((err: BusinessError) => {
              console.error("remove file failed with error message: " + err.message + ", error code: " + err.code);
            });

            console.log(this.filesDir)
            console.log("file dir ==> " + this.filesDir)
            try {
              request.downloadFile(this.context, {
                url: 'https://xxxxx/settings.json?v=1718157761736',
                filePath: this.filesDir + '/helloworld.txt'
              }).then((downloadTask: request.DownloadTask) => {
                downloadTask.on('complete', () => {
                  console.info('download complete');
                  let file = fs.openSync(this.filesDir + '/helloworld.txt', fs.OpenMode.READ_ONLY);
                  let arrayBuffer = new ArrayBuffer(1024);
                  let newFile = fs.openSync(this.filesDir + '/new.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
                  let readLength = 0
                  let readTotalLength = 0
                  let fitstOffset = 0
                  let fileLength = fs.statSync(this.filesDir + '/helloworld.txt').size
                  let contentCount = 1
                  let options: dataPreferences.Options = { name: 'myStore' };
                  this.preferences = dataPreferences.getPreferencesSync(this.context, options);

                  try {
                    while ((readLength = fs.readSync(file.fd, arrayBuffer,
                      {
                        offset: fitstOffset + readTotalLength,
                        length: fileLength > arrayBuffer.byteLength ? 1024 : fileLength
                      })) > 0) {
                      readTotalLength += readLength
                      fs.writeSync(newFile.fd, arrayBuffer, { length: readLength })
                      fileLength -= arrayBuffer.byteLength
                      let buf = buffer.from(arrayBuffer, 0, readLength);
                      this.preferences.putSync('startup' + contentCount, `${buf.toString()}`);
                      let value: dataPreferences.ValueType = this.preferences.getSync('startup' + contentCount, 'string');

                      console.log('首选项' + contentCount + "  " + value.toString())
                      contentCount++
                    }
                  } catch (err) {
                    console.log(err)
                  }
                  fs.close(file)
                  fs.close(newFile)
                })
              }).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}`);
            }
          })
      }
      .width('100%')
    }
    .height('100%')
  }

上述代码已经帮保存了完整的JSON文件,JSON字符串存在沙箱路径的应用文件目录里的new.txt里。

更多关于HarmonyOS 鸿蒙Next中如何下载JSON字符串的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙Next)中,下载JSON字符串可以通过网络请求实现。使用@ohos.net.http模块中的Http类来发送HTTP请求并获取响应数据。以下是一个简单的示例代码,展示如何下载JSON字符串:

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

// 创建Http对象
let httpRequest = http.createHttp();

// 定义请求的URL
let url = 'https://example.com/api/data';

// 发送GET请求
httpRequest.request(url, {
  method: http.RequestMethod.GET,
  header: {
    'Content-Type': 'application/json'
  }
}, (err, data) => {
  if (err) {
    console.error('Request failed:', err);
    return;
  }

  // 获取响应数据
  let response = data.result;
  console.log('Response data:', response);

  // 解析JSON字符串
  try {
    let jsonObj = JSON.parse(response);
    console.log('Parsed JSON:', jsonObj);
  } catch (e) {
    console.error('Failed to parse JSON:', e);
  }
});

此代码通过HTTP GET请求从指定URL获取JSON字符串,并将其解析为JavaScript对象。httpRequest.request方法用于发送请求,JSON.parse用于解析JSON字符串。

在HarmonyOS(鸿蒙)Next中,下载JSON字符串可以通过网络请求实现。你可以使用@ohos.net.http模块中的HttpRequest类来发送HTTP请求并获取JSON数据。以下是一个简单的示例代码:

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

let httpRequest = http.createHttp();
httpRequest.request('https://example.com/data.json', (error, data) => {
  if (error) {
    console.error('Download error:', error);
  } else {
    let jsonString = data.result.toString();
    console.log('Downloaded JSON:', jsonString);
  }
});

在这个示例中,我们发送一个GET请求到指定的URL,并将响应数据转换为字符串。确保在config.json中声明网络权限:

{
  "module": {
    "reqPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  }
}

这样你就可以成功下载并处理JSON字符串了。

回到顶部