打开URI – 无效的URI错误,编码/转义不影响
我正在构建一个YahooFinance Api,并在尝试使用开放URI时不断碰壁。
码:
uri = ("http://ichart.finance.yahoo.com/table.csv?s=#{URI.escape(code)}&a=#{start_month}&b=#{start_day}&c=#{start_year}&d=#{end_month}&e=#{end_day}&f=#{end_year}&g=d&ignore=.csv") puts "#{uri}" conn = open(uri)
错误:
`split': bad URI(is not URI?): http://ichart.finance.yahoo.com/table.csv?s=%255EIXIC&a=00&b=1&c=1994&d=09&e=14&f=2014&g=d&ignore=.csv} (URI::InvalidURIError)
我已经尝试了URI.unescape(code)
,输出code
为^IXIC
,以及保留任何URI
方法, code
将通过%5EIXIC
。
在阅读堆栈溢出后,我尝试了这两种方法都无济于事:
uri = URI.parse(URI.encode(url.strip))
safeurl = URI.encode(url.strip)
即使在查看了另一个ruby yahoo-finance gem的代码之后, 在这里 ,我似乎无法找到解决方案。 任何帮助是极大的赞赏。 谢谢
编辑:当我用单引号手动输入url时,我可以使用open(uri)
。 做双引号,(用于插入ruby物体),在这里发挥作用?
不要试图将变量注入URL。 如果它们包含需要根据规范进行编码的字符,则不会通过插值进行编码。 相反,利用适合工作的工具,如Ruby的URI类或Addressable :: URI gem。
有关如何使用经过良好测试的轮子执行此操作,请参阅“ 如何发布包含花括号和冒号的URL ”。
在你的情况下,这样的东西将起作用:
require 'uri' code = 'qwer3456*&^%' start_month = 1 start_day = 1 start_year = 2014 end_month = 12 end_day = 31 end_year = 2015 uri = URI.parse("http://ichart.finance.yahoo.com/table.csv") uri.query = URI.encode_www_form( { 'g' => 'd', 'ignore' => '.csv', 's' => code, 'a' => start_month, 'b' => start_day, 'c' => start_year, 'd' => end_month, 'e' => end_day, 'f' => end_year } ) uri.to_s # => "http://ichart.finance.yahoo.com/table.csv?g=d&ignore=.csv&s=qwer3456*%26%5E%25&a=1&b=1&c=2014&d=12&e=31&f=2015"
虽然我不认为API端点是正确的,但代码对我有用:
[1] pry(main)> uri = URI("http://ichart.finance.yahoo.com/table.csv?s=%255EIXIC&a=00&b=1&c=1994&d=09&e=14&f=2014&g=d&ignore=.csv") => # [3] pry(main)> Net::HTTP.get(uri) => "\nYahoo! - 404 Not Found \n\n\nSorry, the page you requested was not found.
\nPlease check the URL for proper spelling and capitalization. If\nyou're having trouble locating a destination on Yahoo!, try visiting the\nYahoo! home\npage or look through a list of Yahoo!'s\nonline services. Also, you may find what you're looking for\nif you try searching below.
\n\nPlease try Yahoo!\nHelp Central if you need more assistance.
\nCopyright © 2014 Yahoo! Inc.\nAll rights reserved. Privacy\nPolicy - Terms\nof Service
\n\n"
看起来你的问题是ignore=.csv
部分。
我的意思是这可能是尝试将其编码为域扩展。 可能你应该删除点来解决问题。