3

ルビー1.9.2-p290を使用します。次のようなURIを解析しようとして問題が発生しました。

require 'uri'
my_uri = "http://www.anyserver.com/getdata?anyparameter={330C-B5A2}"
the_uri = URI.parse(my_uri)

次のエラーを発行します。

URI::InvalidURIError: bad URI(is not URI?)

このように毎回中括弧をエンコードするのとは異なる解決策が必要です。

new_uri = URI.encode("http://www.anyserver.com/getdata?anyparameter={330C-B5A2}")
=> "http://www.anyserver.com/getdata?anyparameter=%7B330C-B5A2%7D"

これで、通常どおりnew_uriを解析できますが、必要になるたびにこれを実行する必要がありました。毎回それを行わずにこれを達成するための最も簡単な方法は何ですか?

私はそれを解決したのとまったく同じようにこれを見ていなかったので、私は自分の解決策を投稿します。


# Accepts URIs when they contain curly braces
# This overrides the DEFAULT_PARSER with the UNRESERVED key, including '{' and '}'
module URI
  def self.parse(uri)
    URI::Parser.new(:UNRESERVED => URI::REGEXP::PATTERN::UNRESERVED + "\{\}").parse(uri)
  end
end

これで、中括弧を含むuriでURI.parse(uri)を使用でき、エラーはスローされません。

4

2 に答える 2

5
# Need to not fail when uri contains curly braces
# This overrides the DEFAULT_PARSER with the UNRESERVED key, including '{' and '}'
# DEFAULT_PARSER is used everywhere, so its better to override it once
module URI
  remove_const :DEFAULT_PARSER
  unreserved = REGEXP::PATTERN::UNRESERVED
  DEFAULT_PARSER = Parser.new(:UNRESERVED => unreserved + "\{\}")
end

同じ問題に続いて、DEFAULT_PARSERはどこでも使用されるため、URI#parseメソッドの代わりに完全に置き換える方がよいでしょう。さらに、これにより、毎回新しいパーサーオブジェクトをインスタンス化するためのメモリの割り当てが回避されます。

于 2012-01-13T15:22:40.940 に答える
2

RFC 1738- http: //www.faqs.org/rfcs/rfc1738.htmlは、中括弧をエンコードする必要があることを意味します

Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
reserved characters used for their reserved purposes may be used
unencoded within a URL.
于 2012-01-13T03:53:41.613 に答える