Last active
September 17, 2015 09:19
-
-
Save kgalli/8c5e540b24b6c8f52eaf to your computer and use it in GitHub Desktop.
net/http https example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
def fetch(uri_str, limit = 10) | |
# You should choose a better exception. | |
raise ArgumentError, 'too many HTTP redirects' if limit == 0 | |
#response = Net::HTTP.get_response(URI(uri_str)) | |
uri = URI(uri_str) | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = true | |
get_request = Net::HTTP::Get.new(uri, initheader = { 'Accept' => 'application/json' }) | |
response = http.request(get_request) # Net::HTTPResponse object | |
case response | |
when Net::HTTPSuccess then | |
response | |
when Net::HTTPRedirection then | |
location = response['location'] | |
warn "redirected to #{location}" | |
fetch(location, limit - 1) | |
else | |
response.value | |
end | |
end | |
print fetch('https://api.github.com/repos/vmg/redcarpet/issues?state=closed').body |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment