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

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

Source: Dev.to

Context ## Description ## Solution ## Key Takeaways ## Written by Bilal Basboz Read the original article:How to read data when an HTTP request returns a JSON file and dataL2 access is successful? 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? 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"). 2.Use this method to read the JSON file returned by an HTTP request: Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well For further actions, you may consider blocking this person and/or reporting abuse COMMAND_BLOCK: // 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 COMMAND_BLOCK: // 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); } }); }) } COMMAND_BLOCK: // 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); } }); }) } CODE_BLOCK: // 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 CODE_BLOCK: // 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.. } } CODE_BLOCK: // 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.. } } - 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. - Use this method to read a local JSON file: - 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").