获取响应的编码转换

获取响应的编码转换

本文介绍了获取响应的编码转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React Native 方法中,我正在获取以 ISO-8859-1 编码的 xml.

Inside a React Native method I'm fetching a xml encoded in ISO-8859-1.

只要完成提取,我就会尝试将其转换为 UTF-8.

As long as the fetching is completed I'm trying to convert it to UTF-8.

这里是代码:

const iconv = require('iconv-lite');

fetch('http://www.band.uol.com.br/rss/colunista_64.xml', {
      headers: {
        "Content-type": "text/xml; charset=ISO-8859-1"
      }
})
.then(res=>res.text()})
.then(text => {
   const decodedText = iconv.decode(Buffer.from(text, 'latin1'), 'latin1')
  , output = iconv.encode(decodedText, 'utf8')
   console.log(output.toString())
})

问题是:正文的所有特殊字符都被替换为¿½"

The problem is: all especial characters of the body is being replaced by "¿½"

对于转换,我使用包 iconv-lite

对于这个问题有什么更好的解决方法?

What is the better workaround for this problem?

推荐答案

最好的解决方法是使用 res.arrayBuffer() 代替 res.text(),如long Buffer 构造函数接受 ArrayBuffer

The best workaround is to use res.arrayBuffer() instead res.text(), as long the Buffer constructor accepts ArrayBuffer

代码:

fetch('http://www.band.uol.com.br/rss/colunista_64.xml')
      .then(res => res.arrayBuffer())
      .then(arrayBuffer => iconv.decode(new Buffer(arrayBuffer), 'iso-8859-1').toString())
      .then(converted => console.log(converted))

这篇关于获取响应的编码转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 19:17