Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string with white space into URL

I'm using ruby and googles reverse geocode yql table to ideally automate some search query I have. The problem I hit is turning the query into a legal url format. The issue is that the encoding I'm using is returning illegal urls. The query I'm running is as follows

query="select * from google.geocoding where q='40.714224,-73.961452'" 
pQuery= CGI::escape(query)

The eventual output for the processed query looks like this

http://query.yahooapis.com/v1/public/yql?q=select+%2A+from+google.geocoding+where+q%3D%2740.3714224%2C--73.961452%27+format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=

Alas the url is illegal. When checking what the query shoud look like in the YQL console I get the following

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20google.geocoding%20where%20q%3D%2240.714224%2C-73.961452%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=

As you can hopefully see :), the encoding is all wrong. I was wondering does anyone know how I can go about generating correct urls.

like image 888
Steve Avatar asked Jun 27 '10 09:06

Steve


People also ask

How do I pass a whitespace in a URL?

Our recommendation is to avoid using spaces in URLs, and instead use hyphens to separate words. If you are unable to do this, make sure to encode whitespace using "+" or "%20" in the query-string, and using "%20" within the rest of the URL.

Is whitespace valid in URL?

Spaces are not allowed in URLs. They should be replaced by the string %20. In the query string part of the URL, %20 can be abbreviated using a plus sign (+).

How do you turn a string into a URL?

You should first convert your string into a URI , then convert the URI into a URL . For example: String str = "http://google.com"; URI uri = new URI(str); URL url = uri. toURL();

What is %20 in query string?

URLs are encoded as RFC 1738 which specifies %20 . Show activity on this post. According to the W3C (and they are the official source on these things), a space character in the query string (and in the query string only) may be encoded as either " %20 " or " + ".


1 Answers

If you want to escape a URI, you should use URI::escape:

require 'uri'

URI.escape("select * from google.geocoding where q='40.714224,-73.961452'")
# => "select%20*%20from%20google.geocoding%20where%20q='40.714224,-73.961452'"
like image 104
Jörg W Mittag Avatar answered Oct 11 '22 12:10

Jörg W Mittag