目录

How do I convert the network data obtained by Axios from the GBK format to the UTF-8 format?

Use @ohos.util (util) to convert the GBK format to the UTF-8 format. The implementation is as follows:

1. Import axios and util.

2. Use Axios to obtain network data, and set the data type to ARRAY_BUFFER.

3. Use util.TextDecoder to perform decoding.

4. Use LazyForEach to display the decoded data in a list.

The code snippet is as follows:

import { util } from '@kit.ArkTS';
import axios, { AxiosResponse } from '@ohos/axios';

const URL: string = 'xxx';

@Entry
@Component
struct FriendsBook {

  build() {
  }

  aboutToAppear() {
    axios<string, AxiosResponse<string>, null>({
      method: 'get',
      url: URL,
      // When using the util.TextDecoder method, the encoding and decoding formats must be consistent,
      // so the data type needs to be set to ARRAY_BUFFER when retrieving, otherwise garbled characters will appear.
      responseType: 'ARRAY_BUFFER'
    })
      .then((res: AxiosResponse) => {
        // First, use create to construct a TextDecoder instance and set the encoding format to gbk.
        const textDecoder = util.TextDecoder.create('gbk', { ignoreBOM: true });
        // Next, use the decodeWithStream method to decode the input parameters and output the corresponding UTF-8 formatted text string.
        // The parameters passed in must be in Uint8Array format, so the obtained data needs to be converted to an array type using the Uint8Array method.
        const result = new Uint8Array(res.data);
        const resultString = textDecoder.decodeToString(result, { stream: false });
        // Parse JSON strings.
        const jsonResult = JSON.parse(resultString) as string;
      })
  }
}