React Native Fetch请求返回Windows-1250编码乱码问题求助
React Native Fetch处理Windows-1250编码响应乱码问题
问题核心:服务器返回的XML采用Windows-1250编码,但React Native的response.text()默认按UTF-8解析,导致特殊字符(如á、ž、ú)显示为�乱码。
解决方案
通过手动处理响应的二进制数据,指定对应编码解码:
fetch('http://localhost:444/xml', { method: 'POST', headers: { 'STW-Authorization': 'Basic YmFybmk6YmFybmkxNTY=', 'Content-Type': 'text/xml', }, }) .then(response => response.arrayBuffer()) .then(buffer => { // 使用Windows-1250编码解码二进制数据 const decoder = new TextDecoder('windows-1250'); const decodedXML = decoder.decode(buffer); console.log(decodedXML); // 后续可根据需求解析XML内容 }) .catch(error => console.error('请求异常:', error));
原理说明
response.arrayBuffer()获取原始二进制响应数据,避免默认的UTF-8自动解码TextDecoder是React Native支持的原生API,传入windows-1250参数可正确解码中欧字符集的内容,还原note字段的正确文本:Nebol nájdené žiadny súbor pre spracovanie.
内容的提问来源于stack exchange,提问作者barnitestacc
相关产品推荐
相关产品推荐

