WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

QuickApp 快应用中 或 nodejs 中 API接品调用时 GBK转UTF8

Posted on 2020-11-02 15:44  WebEnh  阅读(280)  评论(0编辑  收藏  举报

请求接口地址:https://doc.quickapp.cn/features/system/fetch.html?h=fetch

第一步,安装包:

npm install iconv-lite
  async onInit() {
    var prompt = require('@system.prompt');
    {
      // 这是转换前的GBK
      var resultFetchOld = await fetch.fetch({
        url: 'http://ip.ws.126.net/ipquery',
        responseType: 'text',
        method: 'GET',
        headers: {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'cache-control': 'no-cache',
        'pragma': 'no-cache',},
      });
      console.log('显示转换前的结果: ', resultFetchOld.data.data, '4秒后显示转换后的结果');
      // 显示转换前的结果
      setTimeout(function () {
        var htmlStr = '显示转换前的结果: ' + resultFetchOld.data.data + ',4秒后显示转换后的结果'
        prompt.showToast({ message: htmlStr });
      }, 0);
    }

    var resultFetch = await fetch.fetch({
      url: 'http://ip.ws.126.net/ipquery',
      responseType: 'arraybuffer',
      // responseType: 'text',
      method: 'GET',
      headers: {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'cache-control': 'no-cache',
        'pragma': 'no-cache',
      },
    });

    // console.log('resultFetch', resultFetch);
    // console.log('resultFetch.data.data', resultFetch.data.data)
    // console.log('resultFetch.data.data-stringify', JSON.stringify(resultFetch.data.data));

    //这里是引入包
    const Buffer = require('buffer').Buffer; // 这个包为 nodejs 自带,无需安装
    const iconvLite = require('iconv-lite');

    // let b1 = new Uint8Array(ipHtmlResult.data.data);
    //Buffer.from(b1,'hex')是把Uint8Array转化成Buffer类型数据
    let htmlStr = iconvLite.decode(Buffer.from(resultFetch.data.data, 'hex'), 'gbk');

    console.log('htmlStr', htmlStr);

    // 显示转换后的结果
    setTimeout(function () {
      htmlStr = '显示转换后的结果: ' + htmlStr
      prompt.showToast({ message: htmlStr });
    }, 4000);
  }

如果未开启 async 支持,请参考 https://doc.quickapp.cn/tutorial/framework/using-async.html?h=async