Using Net::HTTP.get for an https url

Ruby

Ruby Problem Overview


I'm trying to use Net::HTTP.get() for an https URL:

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

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

> can't convert URI::HTTPS into String

What's the deal? I'm using Ruby 1.8.7 (OS X)

Ruby Solutions


Solution 1 - Ruby

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 pointed out in the comments, this is more elegant:

require "open-uri"
@data = URI.parse("https://example.com/some/path").read

Solution 2 - Ruby

EDIT: My approach works, but @jason-yeo's approach is far easier.

It appears as of 2.1.2 the preferred a documented method is as follows (directly quoting the documentation):

> HTTPS is enabled for an HTTP connection by #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 require ‘net/https’ to use > HTTPS. This is no longer true.

Solution 3 - Ruby

In Ruby 2.0.0 and above, simply passing in an uri object with a https url is sufficient to do a HTTPS get request.

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

You may verify this by performing a get request on a domain with 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 method, sets :use_ssl to true when the uri.scheme is "https".

Disclaimer: I understand that the question is for Ruby 1.8.7, but since this is one of the top few search results when one searches for "https ruby", I've decided to answer anyway.

Solution 4 - Ruby

this should look as:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTony StarkView Question on Stackoverflow
Solution 1 - RubystefView Answer on Stackoverflow
Solution 2 - RubyeebbesenView Answer on Stackoverflow
Solution 3 - RubyJason YeoView Answer on Stackoverflow
Solution 4 - RubyVlad KhomichView Answer on Stackoverflow