Ruby URI Percent Encoding
Written by Ben on March 30, 2007 |
4 Comments
4 Comments CGI.escape and URI.escape are both available in the standard Ruby libraries for URL encoding. But which one should you use?
Here’s a quick note about the differences:
irb(main):001:0> require ‘cgi’
=> true
irb(main):002:0> require ‘uri’
=> true
irb(main):003:0> URI.escape(‘Test Hi<>?/&;=:’)
=> “Test%20Hi%3C%3E?/&;=:”
irb(main):004:0> URI.escape(‘Test Hi<>?/&;=:’, ‘&’)
=> “Test Hi<>?/%26;=:”
irb(main):005:0> CGI.escape(‘Test Hi<>?/&;=:’)
=> “Test+Hi%3C%3E%3F%2F%26%3B%3D%3A”
Note that URI.escape fails to encode the ampersand… So definitely use CGI.escape if you want to safely encode a query parameter for net/http calls.
Not only did URI not encode the ampersand but it neglected the /. I noticed this same issue with strings like “3/4″ in a url.
Comment by Phillip Novess — May 3, 2007 @ 8:39 pm
I ran into this same issue when we were constructing a querystring for use with a web service. One of the data values had an & the middle of it which didn’t get encoded with the URI.encode or URI.escape. CGI::escape() did the trick.
Comment by Scott — September 18, 2009 @ 3:44 pm
nice post, thanks for sharing.
I usually don’t post on Blogs but ya forced me to, great info.
Comment by book — January 16, 2010 @ 11:03 am
It is because URI.escape is supposed to operate on whole URIs (which can contain ampersands and slashes) and CGI.escape on query parts.
Comment by Matma Rex — May 6, 2010 @ 5:25 am