【问题标题】:RestClient Parsing URI with Space on Request PathRestClient 解析 URI,请求路径上有空格
【发布时间】:2013-11-28 07:35:12
【问题描述】:

我目前正在编写一个代码,我正在请求一个 URL,请求路径上有空格:

http://example.com/path1/path2/some details.detail?keyword=key word

我正在使用rest-client gem。

url = http://example.com/path1/path2/some details.detail?keyword=key word
RestClient::Request.execute(method: :get, url: url)

但是它会抛出一个错误:

URI::InvalidURIError: bad URI(is not URI?): http://example.com/path1/path2/some details.detail?keyword=key word

文档建议先解析和规范化 URL:

parsed_url = Addressable::URI.parse(url).normalize.to_str
# parsed_url is now: http://example.com/path1/path2/some%20details.detail?keyword=key%20word    
RestClient::Request.execute(method: :get, url: parsed_url)

但错误依然存在。

URI::InvalidURIError: bad URI(is not URI?): http://example.com/path1/path2/some details.detail?keyword=key%20word

它似乎无法解析 url 的 /some details.detail 部分。

有人遇到过同样的问题吗?

【问题讨论】:

    标签: ruby parsing rest rest-client


    【解决方案1】:

    试试URI.encode:

    $ irb
    2.0.0-p247 :001 > require "uri"
     => true 
    2.0.0-p247 :002 > URI.encode("http://example.com/path1/path2/some details.detail?keyword=key word")
     => "http://example.com/path1/path2/some%20details.detail?keyword=key%20word" 
    2.0.0-p247 :003 > 
    

    【讨论】:

    • OP 的问题不在于编码,而在于他在检查什么有效时忘记使用新变量parsed_url。 . .
    • 你确定?他用了parsed_url,“但错误仍然存​​在”后面的错误看起来只是对查询字符串进行了编码。
    • 不是 100% 确定,但我只是按照 OP 的步骤操作,一切正常。仔细看最后一条错误信息,你会发现 URI 和上一步不一样。
    • 啊,我看到他评论了“parsed_url is now...”,看起来不错...不知道! :)
    【解决方案2】:

    在 Ruby 2.0.0 上使用 rest-client 1.6.7 和 addressable 2.3.5,这是一个试图复制您的错误的 irb 会话:

    :001 > require 'rest-client'
     => true
    
    :002 > require "addressable/uri"
     => true
    
    :003 > url = 'http://example.com/path1/path2/some details.detail?keyword=key word'
     => "http://example.com/path1/path2/some details.detail?keyword=key word"
    
    :004 > parsed_url = Addressable::URI.parse(url).normalize.to_str
     => "http://example.com/path1/path2/some%20details.detail?keyword=key%20word"
    
    :005 > RestClient::Request.execute(method: :get, url: parsed_url)
    RestClient::ResourceNotFound: 404 Resource Not Found: <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
    

    根据您自己的解决方案,它似乎可以正常工作。据我所知,要么在调查问题时错过了重复步骤(从一开始就重试,以防万一),或者它可能是您正在使用的两个 gem 之一的旧版本中的一个错误 -在这种情况下,您可以通过安装最新版本来修复它。

    【讨论】:

    • 感谢尼尔的评论。上面的代码有效。但是,当尝试将其实现到实际 URL:http://muse.aucklandmuseum.com/databases/Muscat/MP 98.detail?keywords=Shell Oil New Zealand Hauraki Gulf 时,它会中断。有什么想法吗?
    • 仔细查看它拒绝的 URL。您正在获得重定向,其中也包含空格,rest-client 正在尝试自动关注并且 然后 不处理它。 . .这似乎更难。如果我直接转到重定向 URL,我会从服务器获得 404,因此连接正常。
    • 我为这个问题创建了一个 pull request 给 rest-client gem。现在,我做了一个猴子路径来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2023-02-03
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多