Error when using URI.escape in ruby - 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

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"))

Related

undefined local variable or method `http' for main:Object (NameError)

File: nethttp.rb
require 'uri'
require 'net/http'
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
uri = URI('http://localhost/events',:headers => headers)
res = Net::HTTP.get_response(uri)
puts res.body if res.is_a?(Net::HTTPSuccess)
I'm receiving the error:
undefined local variable or method `http' for main:Object (NameError)
You're using the local variable http which is not declared anywhere in the code. If you want to create an instance of Net::HTTP you need to use the "new" method:
require 'uri'
require 'net/http'
# URI only takes one argument!
uri = URI('http://localhost/events')
http = Net::HTTP.new(uri)
# not sure what this is supposed to do since you're requesting a
# HTTP uri and not HTTPS
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
# ...
But you might want to consider using Net::HTTP.start which opens a connection and yields it to the block:
require 'uri'
require 'net/http'
uri = URI('http://localhost/events')
# Opens a persisent connection to the host
Net::HTTP.start(uri.host, uri.port, verify_mode: OpenSSL::SSL::VERIFY_NONE) do |http|
headers = { "X-FOO" => "Bar" }
request = http.get(uri)
headers.each do |key, value|
request[key] = value
end
response = http.request(request)
# consider using a case statement
if response.is_a?(Net::HTTPSuccess)
puts response.body
else
# handle errors
end
end

Why am I getting undefined method error ruby?

require "rubygems"
require "json"
require "net/http"
require "uri"
uri = URI.parse("https://api.website.com/top/inside/end")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
http.use_ssl = true
response = http.request(request)
if response.code == "200"
result = JSON.parse(response.body)
names = Array.new
i = 0
result.each do |doc|
names.insert(i, doc.name)
puts doc["id"] #reference properties like this
puts doc # this is the result in object form
puts ""
puts ""
end
puts names
else
puts "ERROR!!!"
end
Why am I getting undefined method error on variable names inside the for each loop? I cannot understand why
script.rb:18:in `block in ': undefined method `name' for #<Hash:0x0000000002e04c08> (NoMethodError)
line 18,
names.insert(i, doc.name)
doc is a Hash, doc['name'] should works.
in javascript, you can do
doc.name

Making HEAD request in Ruby

I am kind of new to ruby and from a python background
I want to make a head request to a URL and check some information like if the file exists on the server and timestamp, etag etc.,I am not able to get this done in RUBY.
In Python:
import httplib2
print httplib2.Http().request('url.com/file.xml','HEAD')
In Ruby: I tried this and throwing some error
require 'net/http'
Net::HTTP.start('url.com'){|http|
response = http.head('/file.xml')
}
puts response
SocketError: getaddrinfo: nodename nor servname provided, or not known
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:877:in `initialize'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:877:in `open'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:877:in `block in connect'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/timeout.rb:51:in `timeout'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:876:in `connect'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:861:in `do_start'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:850:in `start'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:582:in `start'
from (irb):2
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in `<main>'
I realize this has been answered but I had to go through some hoops, too. Here's something more concrete to start with:
#!/usr/bin/env ruby
require 'net/http'
require 'net/https' # for openssl
uri = URI('http://stackoverflow.com')
path = '/questions/16325918/making-head-request-in-ruby'
response=nil
http = Net::HTTP.new(uri.host, uri.port)
# http.use_ssl = true # if using SSL
# http.verify_mode = OpenSSL::SSL::VERIFY_NONE # for example, when using self-signed certs
response = http.head(path)
response.each { |key, value| puts key.ljust(40) + " : " + value }
I don't think that passing in a string to :start is enough; in the docs it looks like it requires a URI object's host and port for a correct address:
uri = URI('http://example.com/some_path?query=string')
Net::HTTP.start(uri.host, uri.port) do |http|
request = Net::HTTP::Get.new uri
response = http.request request # Net::HTTPResponse object
end
You can try this:
require 'net/http'
url = URI('yoururl.com')
Net::HTTP.start(url.host, url.port){|http|
response = http.head('/file.xml')
puts response
}
One thing I noticed - your puts response needs to be inside the block! Otherwise, the variable response is not in scope.
Edit: You can also treat the response as a hash to get the values of the headers:
response.each_value { |value| puts value }
headers = nil
url = URI('http://my-bucket.amazonaws.com/filename.mp4')
Net::HTTP.start(url.host, url.port) do |http|
headers = http.head(url.path).to_hash
end
And now you have a hash of headers in headers

Unable to make HTTP Delete request in my ruby code using Net::HTTP

Im using Net::HTTP in my ruby code to make http requests. For example to make a post request i do
require 'net/http'
Net::HTTP.post_form(url,{'email' => email,'password' => password})
This works. But im unable to make a delete request, i.e.
require 'net/http'
Net::HTTP::Delete(url)
gives the following error
NoMethodError: undefined method `Delete' for Net::HTTP:Class
The documentation at http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html shows Delete is available. So why is it not working in my case ?
Thank You
The documentation tells you that Net::HTTP::Delete is a class, not a method.
Try Net::HTTP.new('www.server.com').delete('/path') instead.
uri = URI('http://localhost:8080/customer/johndoe')
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Delete.new(uri.path)
res = http.request(req)
puts "deleted #{res}"
Simple post and delete requests, see docs for more:
puts Net::HTTP.new("httpbin.org").post("/post", "a=1").body
puts Net::HTTP.new("httpbin.org").delete("/delete").body
This works for me:
uri = URI(YOUR_URL)
req = Net::HTTP::Delete.new(uri, {}) # params on second place
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
http.request req
end

request response with gmail using uri

So far as I can tell the Google::Reader API is working fine, in that it returns an sid successfully. However, lower level interactions with gmail won't run properly:
warning: peer certificate won't be verified in this SSL session
#<Google::Reader::Base:0xb76efa0c
#email="hawat.thufir",
#password="pword",
#sid=
"DQAAAL4AAACq-Wrm1V_anY1sV4r_3kA4EuRax9oTt5z7upD6NNfT0e7bsN-8WA7cQOTt7zypI5fymS9Ux8QTtyu-7xal9c6szb2ZoeBR5dwPH_m7OrBe6ICkKY-dPus0_g5DFW6tckpCZmJIyrP9zfUQKJzGYjnYKJzJEJYFEdvMu756Hl68qeD6AuGKDdFWbyBEvgQGR2oFjkxHYGqwTQ9oHJBfBkMH9hrDl2Q9C_cVE5A-_Bb9RiUy6WuwIbS-pPN56z3XtpA">
#<URI::HTTPS:0xb76e7988 URL:https://hawat.thufir:pword#gmail.com>
#<Net::HTTP gmail.com:443 open=false>
#<Net::HTTP::Get GET>
["Basic aGF3YXQudGh1ZmlyOmRldm90Y2hrYQ=="]
#<Net::HTTP::Get GET>
/usr/lib/ruby/1.8/net/http.rb:1060:in `request': undefined method `closed?' for nil:NilClass (NoMethodError)
from ./req_uri.rb:23
code:
#!/usr/bin/ruby -w
require 'rubygems'
require 'google/reader'
require 'pp'
require 'net/http'
require 'net/https'
require 'uri'
require 'yaml'
yml = YAML.load_file 'login.yml'
user = yml["user"]
pword = yml["pword"]
pp Google::Reader::Base.establish_connection(user, pword)
uri = URI.parse "https://#{user}:#{pword}#gmail.com"
pp uri
pp http = Net::HTTP.new(uri.host, uri.port)
pp request = Net::HTTP::Get.new(uri.request_uri)
pp request.basic_auth(user, pword)
pp request
response = http.request(request)
So, the question is, should the request be basically empty when printed? What's wrong with sending the request to the response? That seems to be correct so far as I can ascertain. What am I missing?

Resources