Topic: Net::HTTP not working with https?

I made a method to request and parse json. It works with one of the api's I connect to. However, it does not work with the gist api. I think it is because the gist api uses ssl (https). Any help to modify my code to work with both http and https? Is that even the issue?

JSON::ParserError in PagesController#index
743: unexpected token at '<html>
<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>nginx/1.0.4</center>
</body>
</html>
'
def json_api_pull(url)
  resp = Net::HTTP.get_response(URI.parse(url))
  data = resp.body
  result = JSON.parse(data)
    
  return result
end

Thank you!

Learning rails, one day at a time.

http://keilmiller.com

Re: Net::HTTP not working with https?

Anyone?

Learning rails, one day at a time.

http://keilmiller.com

Re: Net::HTTP not working with https?

Found a solution posted on a blog here. I don't quite understand all of it as I'm still a ruby nubie, but I am able to work with it. It does exactly what I wanted... parsing json from an http or https request. Next step is for me to add caching so I'm not making these api requests like nuts.

I'll post the solution here for readability and just in case of a 404:

require 'net/https'
require 'json'

url = URI.parse('https://api.github.com/repos/technoweenie/faraday')

response = Net::HTTP.start(url.host, use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_NONE) do |http|
  http.get url.request_uri, 'User-Agent' => 'MyLib v1.2'
end

case response
when Net::HTTPRedirection
  # repeat the request using response['Location']
when Net::HTTPSuccess
  repo_info = JSON.parse response.body
else
  # response code isn't a 200; raise an exception
  response.error!
end

Last edited by tuscanidream (2012-01-25 22:41:49)

Learning rails, one day at a time.

http://keilmiller.com