【问题标题】:URI encoding not workingURI 编码不起作用
【发布时间】:2013-08-21 18:34:57
【问题描述】:

在 Rails 应用上,我需要解析 uris

a = 'some file name.txt'
URI(URI.encode(a)) # works

b = 'some filename with :colon in it.txt'
URI(URI.encode(b)) # fails URI::InvalidURIError: bad URI(is not URI?): 

如何安全地将文件名传递给包含特殊字符的 URI?为什么编码对冒号不起作用?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    URI.escape(或encode)采用可选的第二个参数。这是一个匹配所有应该转义的符号的正则表达式。要转义您可以使用的所有非单词字符:

    URI.encode('some filename with :colon in it.txt', /\W/)
    #=> "some%20filename%20with%20%3Acolon%20in%20it%2Etxt"
    

    encode 有两个预定义的正则表达式:

    URI::PATTERN::UNRESERVED  #=> "\\-_.!~*'()a-zA-Z\\d"
    URI::PATTERN::RESERVED    #=> ";/?:@&=+$,\\[\\]"
    

    【讨论】:

    • 更通用的方法是使用URI.encode('some filename with :colon in it.txt', Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))。有关详细信息,请参见此处:stackoverflow.com/questions/2834034/….
    【解决方案2】:
    require 'uri'
    
    url = "file1:abc.txt"
    p URI.encode_www_form_component url
    
    --output:--
    "file1%3Aabc.txt"
    
    
    p URI(URI.encode_www_form_component url)
    
    --output:--
    #<URI::Generic:0x000001008abf28 URL:file1%3Aabc.txt>
    
    
    p URI(URI.encode url, ":")
    
    --output:--
    #<URI::Generic:0x000001008abcd0 URL:file1%3Aabc.txt>
    

    为什么编码对冒号不起作用?

    因为编码/转义被破坏了。

    【讨论】:

      【解决方案3】:

      问题似乎是冒号前面的空格,'lol :lol.txt' 不起作用,但 'lol:lol.txt' 起作用。
      也许您可以将空格替换为其他内容。

      【讨论】:

        【解决方案4】:

        使用Addressable::URI::encode

        require "addressable/uri"
        
        a = 'some file name.txt'
        Addressable::URI.encode(Addressable::URI.encode(a))
        # => "some%2520file%2520name.txt"
        
        b = 'some filename with :colon in it.txt'
        Addressable::URI.encode(Addressable::URI.encode(b)) 
        # => "some%2520filename%2520with%2520:colon%2520in%2520it.txt"
        

        【讨论】:

        • %2520 是双重编码。 %20 是空格的编码。然后,如果您对字符串“%20”进行编码,则“%”符号的编码为 %25,即为“%25”+“20”或“%2520”。您不想对字符串进行双重编码。您还需要:gem install addressable。但还要注意,冒号未在输出中编码。
        • @7stud 你是对的..但是这个 gem 目前是 URI 的替代品..我只是试图向 OP 展示 URI 无法实现的东西可以使用这个Addressable 来完成... :)
        【解决方案5】:

        如果你想从给定的字符串中转义特殊字符。最好用

        esc_uri=URI.escape("String with special character")
        

        结果字符串是 URI 转义字符串,可以安全地将其传递给 URI。 请参阅 URI::Escape 了解如何使用 URI 转义。希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多