'Open-Uri Alternative - Getting a response from a website

The following code works in Ruby 1.9.3p-551

require "open-uri"

res = open("http://example.com/version").read

p res => {"buildNumber": 2496, "buildDate": "2015-09-29 11:18:02 +0200", "timestamp": 1443639212 }

In any Ruby version higher than 1.9.3 I get the following error;

from /Users/imac/.rbenv/versions/2.1.0/lib/ruby/2.1.0/net/http/response.rb:357:in `finish': incorrect header check (Zlib::DataError)

I need to use a higher version as this will be used in a Rails 4 app. Any ideas for alternatives?



Solution 1:[1]

Turns out the gzip encoding is not accepted by default. Or at least that's what I'm guessing. The following works.

res = open("http://someurl.com/version", "Accept-Encoding" => "plain").read

Interesting how this changed from Ruby 2.0.0+

Solution 2:[2]

Another neat solution for this.

require 'rest-client'

url = "http://example.com/version"

def get_response(url)
  begin
    return RestClient.get(url, {:accept => :json})
  rescue RestClient::GatewayTimeout 
    "GatewayTimeout"
  rescue RestClient::RequestTimeout
    "RequestTimeout"
  rescue SocketError
    "SocketError"
  end
end   

p get_response(url)

# => "{\"buildNumber\": 2535, \"buildDate\": \"2015-09-30 17:41:42 +0200\", \"timestamp\": 1444085042 }"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2