Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when using URI.escape in ruby

Tags:

ruby

I'm trying to simply escape an URL with spaces and then do a GET request to that URL in Ruby.

The error I have is

/Users/user/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/net/http.rb:393:in `get_response': undefined method `host' for "http://google.com/?this%20is%20a%20stromg%20with%20spaces":String (NoMethodError)
from test_url.rb:6:in `<main>'

This is the current code

require 'rubygems'
require 'net/http'

uri = URI.escape("http://google.com/?this is a string with spaces")
res = Net::HTTP.get_response(uri)
puts res.body if res.is_a?(Net::HTTPSuccess) 

Net::HTTP.start(uri.host, uri.port) do |http|
  request = Net::HTTP::Get.new uri.request_uri

  response = http.request request # Net::HTTPResponse object
end
like image 432
Martin Avatar asked May 26 '26 01:05

Martin


1 Answers

URI.escape just escapes it, and nothing else. You need an actual instance of a URI to pass to get_response:

uri = URI.parse(URI.escape("http://google.com/?this is a string with spaces"))
like image 90
rfunduk Avatar answered May 27 '26 19:05

rfunduk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!