我正在从远程位置读取CSV文件,然后解析它以存储到本地集合中,但是,我收到以下错误并且响应变为一些垃圾字符
Encoding::UndefinedConversionError: "\xD0" from ASCII-8BIT to UTF-8
以下是从远程位置获取csv的代码
uri = URI.parse(site_url)
data = {'token' => "xxxxxxxxxxxxxx"}
req = Net::HTTP::Get.new(uri.path)
req.set_form_data(data)
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme =='https'
pem = File.read("#{Rails.root}/config/ca-certificates.crt")
http.use_ssl = true
http.cert = OpenSSL::X509::Certificate.new(pem)
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
response = http.start do |httpvar|
httpvar.request(req)
end
if response.kind_of?(Net::HTTPRedirection)
headers = {'Content-Type' => "text/csv; ecoding=utf-8" }
uri = URI.parse(response['location'])
response = open(uri).read
end
CSV.parse(response, headers: true, header_converters: :symbol) do |row|
puts row
end
答案 0 :(得分:0)
来自Encoding error while writing data from excelfile to database (mysql)
尝试添加
# ecoding: utf-8
到你的.rb文件,或者使用magic_encoding gem
答案 1 :(得分:0)
我认为当您在响应上调用CSV.parse
时会发生此错误。在解析之前,您可以在response
字符串上强制执行正确的编码,如下所示:
response.force_encoding(Encoding::UTF_8)
CSV.parse(response, headers: true, header_converters: :symbol) do |row|
puts row
end