服务应该从多个源读取 XML 文件
response = HTTParty.get(url)
if response.code == 200
if response.headers['content-type'] and response.headers['content-type'].to_s.downcase.include?('utf-8')
@xml = response.body
else
@xml = response.body.force_encoding("ISO-8859-1").encode("UTF-8")
end
end
实际上,此代码仅在 XML 采用 UTF-8
或 ISO-8859-1
时才有效。
如何将任何类型的源文件转换为 UTF-8
?
还有,当 content-type
和 xml header tag
没有指定编码时,有没有办法知道响应的编码?
最佳答案
您可以通过调用encoding
来获取字符串的编码:
"some string".encoding
#=> #<Encoding:UTF-8>
您可以通过调用 encode
并传入编码来对字符串进行编码:
"some string".encode(Encoding::ISO_8859_1)
关于ruby-on-rails - 如何将任何 HTTParty.get 响应转换为 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20222707/