Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby/Rails, how can I encode/escape special characters in URLs?

How do I encode or 'escape' the URL before I use OpenURI to open(url)?

We're using OpenURI to open a remote url and return the xml:

getresult = open(url).read

The problem is the URL contains some user-input text that contains spaces and other characters, including "+", "&", "?", etc. potentially, so we need to safely escape the URL. I saw lots of examples when using Net::HTTP, but have not found any for OpenURI.

We also need to be able to un-escape a similar string we receive in a session variable, so we need the reciprocal function.

like image 781
jpw Avatar asked Feb 11 '11 09:02

jpw


People also ask

What does CGI escape do?

CGI. escape is for escaping a URL value in the query string. All characters that don't fall into the ALPHA, DIGIT, '_', '-', '. ' and ' ' character set are escaped.

How do you escape an HTML URL?

The link would then be technically broken. Regardless, you basically just need to replace the percents % by their URL-encoded representation %25 (in other words: just encode the URL twice).

How do you exit a special character in a URL in Java?

Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server.


1 Answers

Don't use URI.escape as it has been deprecated in 1.9.

Rails' Active Support adds Hash#to_query:

 {foo: 'asd asdf', bar: '"<#$dfs'}.to_query
 # => "bar=%22%3C%23%24dfs&foo=asd+asdf"

Also, as you can see it tries to order query parameters always the same way, which is good for HTTP caching.

like image 200
Ernest Avatar answered Sep 24 '22 08:09

Ernest