Using Net :: HTTP.get for https url

I am trying to use Net::HTTP.get() for the https url:

 @data = Net::HTTP.get(uri, Net::HTTP.https_default_port()) 

However, when I try to print the results, I get the following result:

cannot convert URI :: HTTPS to string

What a deal? I am using Ruby 1.8.7 (OS X)

+60
ruby
Apr 26 '11 at 6:28
source share
4 answers

Original answer:

 uri = URI.parse("https://example.com/some/path") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true @data = http.get(uri.request_uri) 

As stated in the comments, this is more elegant:

 require "open-uri" @data = URI.parse("https://example.com/some/path").read 
+109
Apr 26 2018-11-11T00:
source

EDIT: my approach works, but the @ jason-yeo approach is much simpler.

It seems that from 2.1.2, the preferred documented method is as follows (directly quoting the documentation ):

HTTPS is enabled for an HTTP connection using #use_ssl =.

 uri = URI('https://secure.example.com/some_path?query=string') Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| request = Net::HTTP::Get.new uri response = http.request request # Net::HTTPResponse object end 

In previous versions of Ruby, you would need to use 'net / https to use HTTPS. This is no longer the case.

+21
Jun 22 '14 at 4:45
source

In Ruby 2.0.0 and later, just passing a uri object with an https URL is enough to execute an HTTPS request.

 uri = URI('https://encrypted.google.com') Net::HTTP.get(uri) 

You can verify this by completing a request for an expired certificate.

 uri = URI('https://expired.badssl.com/') Net::HTTP.get(uri) # OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=error: certificate verify failed 

It was introduced by this commit in Ruby 2.0.0.

The get_response method, which is called by the Net::HTTP.get , sets :use_ssl to true when uri.scheme "HTTPS".

Disclaimer: I understand that the question is about Ruby 1.8.7, but since this is one of the best search results when you search for "https ruby", I decided to answer anyway.

+8
Apr 11 '16 at 8:48
source

it should look like this:

 uri.port = Net::HTTP.https_default_port() @data = Net::HTTP.get(uri) 
+4
Apr 26 '11 at 6:40
source



All Articles