DEV Community

HarmonyOS
HarmonyOS

Posted on

How to read data when an HTTP request returns a JSON file and dataL2 access is successful?

Read the original article:How to read data when an HTTP request returns a JSON file and dataL2 access is successful?

Context

Through an HTTP GET request, data can be successfully called and returned. However, when the request returns content in JSON format, it cannot be directly read. How can we achieve reading the response data from a JSON file?

Description

  • JSON is used for parsing and generation.
  • The file returned by the HTTP request can be obtained as text through requestInStream, as described for initiating an HTTP streaming request.

Solution

First, use requestInStream to obtain the text, then stream the data through on("dataReceive"), and integrate the text content to convert it into JSON data using on("dataEnd").

// Here are the necessary imports
import { http } from '@kit.NetworkKit';
import util from '@ohos.util';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

// Here is the function
async httpTest1(): Promise<object> {
    return new Promise((resolve: Function, reject: Function) => {
      let res = new ArrayBuffer(0);
      let httpRequest = http.createHttp();

      httpRequest.on('dataReceive', (data: ArrayBuffer) => {
        const newRes = new ArrayBuffer(res.byteLength + data.byteLength);
        const resView = new Uint8Array(newRes);
        resView.set(new Uint8Array(res));
        resView.set(new Uint8Array(data), res.byteLength);
        res = newRes;
        console.info('res length: ' + res.byteLength);
      });

      httpRequest.on('dataEnd', () => {
        try {
          let textDecoderOptions: util.TextDecoderOptions = {
            ignoreBOM: true
          }
          let decoder = util.TextDecoder.create('utf-8', textDecoderOptions);
          let str = decoder.decodeToString(new Uint8Array(res.slice(3)));
          let json_str: object = JSON.parse(str);
          resolve(json_str);
        } catch (err) {
          hilog.error(0x0000, 'Page2', `error: ${(err as BusinessError)}`);
          reject(err);
        }
      });

      httpRequest.requestInStream('https://www.example.com/html/app/updateVersion.json', {
        method: http.RequestMethod.GET,
        header: {
          'Content-Type': 'application/json'
        },
        connectTimeout: 6000,
        readTimeout: 6000,
      }, (err, data) => {
        if (err) {
          reject(err);
        }
      });
    })
  }
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  1. Use this method to read a local JSON file:
   // import for Context
   import { common } from '@kit.AbilityKit';
   import { buffer } from '@kit.ArkTS';

   // inside the struct
   @Entry
   @Component
   struct Index {
     context = this.getUIContext().getHostContext() as common.UIAbilityContext;

     aboutToAppear(): void {
       let value = this.context.resourceManager.getRawFileContentSync('data.json');
       if (value) {
         JSON.parse(buffer.from(value.buffer).toString());
       }
     }

     build() {
       // Ui components..
     }
   }
Enter fullscreen mode Exit fullscreen mode

2.Use this method to read the JSON file returned by an HTTP request:

Written by Bilal Basboz

Top comments (0)