Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add encoded query values to a URL?

I am looking for a convenient and functional way to add encoded values to a URL query string in Ruby. Currently, I have:

require 'open-uri'

u = URI::HTTP.new("http", nil, "mydomain.example", nil, nil, "/tv", nil, "show=" + URI::encode("Rosie & Jim"), nil) 

p u.to_s # => "http://mydomain.example/tv?show=Rosie%20&%20Jim"

This isn't what I'm looking for, because I need to get "http://mydomain.example/tv?show=Rosie%20%26%20Jim", so that the show= value is not truncated.

Does Open::URI have another method that would do this? If not, can it be done with any other standard Ruby, or gem?

like image 994
SimonMayer Avatar asked Feb 09 '12 16:02

SimonMayer


People also ask

How do I add a parameter to a URL query?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.

Do query params need to be URL encoded?

Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing them into a URL.

How do you write a valid URL for query string parameters?

A URL which contains a page on your site should NEVER have a "/" after it (e.g. "foo. html/") A URL should always have a single question mark in it "?" URL Query String parameters should be separated by the ampersand "&"


2 Answers

Try with CGI::escape instead of URI::encode . doc here

like image 175
Baldrick Avatar answered Oct 09 '22 18:10

Baldrick


URI.encode_www_form works well and is more convenient for adding multiple arguments

q = URI.encode_www_form("show" => "Rosie & Jim", "series" => "3", "episode" => "4")
u = URI::HTTP.new("http", nil, "mydomain.example", nil, nil, "/tv/ragdoll", nil, q, nil)
like image 27
SimonMayer Avatar answered Oct 09 '22 16:10

SimonMayer