介紹
本示例介紹使用第三方庫的Axios獲取GBK格式的網(wǎng)絡(luò)數(shù)據(jù)時迫横,通過util實現(xiàn)GBK轉(zhuǎn)換UTF-8格式兔沃。該場景多用于需要轉(zhuǎn)換編碼格式的應(yīng)用。
效果圖預(yù)覽
使用說明
直接進入頁面就可獲取GBK格式的用戶名信息并進行解碼操作。
實現(xiàn)思路
- 使用第三方庫Axios獲取網(wǎng)絡(luò)數(shù)據(jù),并將獲取數(shù)據(jù)類型設(shè)置為ARRAY_BUFFER城菊。源碼參考FriendsBook.ets
axios<string, AxiosResponse<string>, null>({
method: "get",
url: URL,
responseType: 'ARRAY_BUFFER'
})
- 使用util.TextDecoder方法進行解碼操作。源碼參考FriendsBook.ets
let textDecoder = util.TextDecoder.create('gbk', { ignoreBOM: true });
let result = new Uint8Array(res.data);
let resultString = textDecoder.decodeWithStream(result, { stream: false });
- 將解碼后的數(shù)據(jù)通過LazyForEach循環(huán)顯示在列表中讹躯。源碼參考FriendsBook.ets
LazyForEach(this.friendsListData, (msg: FriendData) => {
ListItem() {
...
}
})
工程結(jié)構(gòu)&模塊類型
gbktranscoding // har類型
|---pages
|---|---FriendsBook.ets // 視圖層-場景列表頁面