Ruby/Rails - URI格式错误

3

不确定为什么在浏览器中URI可以正常工作,但是我在这里却收到了以下错误:

http://oracleofbacon.org/cgi-bin/xml?a=Kevin Bacon&b=Tom Cruise&u=1&p=google-apps

这是我的代码:
def kb(to)

    uri = "http://oracleofbacon.org/cgi-bin/xml?a=Kevin Bacon&b=#{to.strip}&u=1&p=google-apps"
    doc = Nokogiri::XML(open(uri)) # throws error on this line

    return parse(doc)
end

I get the following error:

in `split': bad URI(is not URI?): http://oracleofbacon.org/cgi-bin/xml?a=Kevin Bacon&b=Tom Cruise&u=1&p=google-apps (URI::InvalidURIError)`

我会以以下方式执行该方法:
kb("Tom Cruise")
1个回答

20

这是因为浏览器像小狗一样异常友好,会竭尽全力渲染页面或解析URL。应用程序不会这样做,因为你必须告诉它如何友好。

你的URL无效,因为其中包含空格。请使用%20替换空格:

irb -f
irb(main):001:0> require 'open-uri'
=> true
irb(main):002:0> open('http://oracleofbacon.org/cgi-bin/xml?a=Kevin%20Bacon&b=Tom%20Cruise&u=1&p=google-apps').read
=> "<?xml version=\"1.0\" standalone=\"no\"?>\n<link><actor>Tom Cruise</actor><movie>A Few Good Men (1992)</movie><actor>Kevin Bacon</actor></link>"

需要转义的字符很容易进行转义:

irb -f
irb(main):001:0> require 'uri'
=> true
irb(main):002:0> URI.escape('http://oracleofbacon.org/cgi-bin/xml?a=Kevin Bacon&b=Tom Cruise&u=1&p=google-apps')
=> "http://oracleofbacon.org/cgi-bin/xml?a=Kevin%20Bacon&b=Tom%20Cruise&u=1&p=google-apps"

非常好用,谢谢。我做了以下操作,但我相信一定有更简洁的方法来将空格替换为%20:#{to.strip.gsub(" ", "%20")} - fulvio
@Fulvio require 'cgi'; CGI::escape("'Stop!' said Fred") # => "%27Stop%21%27+said+Fred" (doc). (或者在Rails中使用h辅助方法)。 - steenslag
@Fulvio,我添加了代码,展示如何处理字符串转义。如果您只知道需要替换一个字符,则使用gsub是可以的。除此之外,您应该利用预先发明的轮子并选择URIAddressable gem,它非常全面。 - the Tin Man

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接