解析流式请求返回数据时,需要将其通过utf-8格式编码转换为字符串才能正常显示,但是过程出现了乱码“�”,怎么解决呢?
let httpRequest = http.createHttp()
httpRequest.on("dataReceive", (data: ArrayBuffer) => {
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let uin8 = new Uint8Array(data)
this.message += textDecoder.decodeToString(uin8, {stream: false})
});
httpRequest.on("dataEnd", () => {
console.info("Receive dataEnd !");
httpRequest.destroy();
}); 由以上问题定位分析可知,以下结论:
综合上面分析结论,需要进行以下两步修改:
1、util.TextDecoder的TextDecoderOptions配置应该放在全局作用域,而不是放在流式响应事件方法当中。这样避免每次解析字节流时都会重新创建TextDecoderOptions,缓冲区不会被重置。
2、util.TextDecoder.decodeToString解析数据的时候需要配置解析相关参数DecodeToStringOptions.stream设置为true,当解码字节流时,如果遇到不完整序列,会将该序列保存至缓冲区。
代码修改如下:
import { util } from '@kit.ArkTS';
import { http } from '@kit.NetworkKit';
@Entry
@Component
struct StreamDataDecodeDemo {
message: string = '';
build() {
RelativeContainer() {
Text('流式解码测试')
.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(() => {
let httpRequest = http.createHttp();
let options: http.HttpRequestOptions = {
method: http.RequestMethod.POST,
extraData: 'data to send',
};
httpRequest.requestInStream('EXAMPLE_URL', options, (err: BusinessError<void>, data: number) => {
if (!err) {
console.info('requestInStream OK! ResponseCode is ' + JSON.stringify(data));
} else {
console.error('requestInStream ERROR : err = ' + JSON.stringify(err));
}
});
// 放在流式请求外部,防止在流式请求中每次接收到字节序列均创建,造成缓冲字节序列丢失。
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
};
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
httpRequest.on('dataReceive', (data: ArrayBuffer) => {
let uin8 = new Uint8Array(data);
this.message += textDecoder.decodeToString(uin8, {stream: true});
});
httpRequest.on('dataEnd', () => {
console.info('Receive dataEnd !');
httpRequest.destroy();
});
})
}
.height('100%')
.width('100%')
}
}