Last active
December 29, 2015 03:19
-
-
Save rubenclopez/7607363 to your computer and use it in GitHub Desktop.
Ruby::RestClient: Handle GET responses
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
# Don't raise exceptions but return the response | |
RestClient.get('http://example.com/resource'){|response, request, result| response } | |
➔ 404 Resource Not Found | text/html 282 bytes | |
# Manage a specific error code | |
RestClient.get('http://my-rest-service.com/resource'){ |response, request, result, &block| | |
case response.code | |
when 200 | |
p "It worked !" | |
response | |
when 423 | |
raise SomeCustomExceptionIfYouWant | |
else | |
response.return!(request, result, &block) | |
end | |
} | |
# Follow redirections for all request types and not only for get and head | |
# RFC : "If the 301, 302 or 307 status code is received in response to a request other than GET or HEAD, | |
# the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, | |
# since this might change the conditions under which the request was issued." | |
RestClient.get('http://my-rest-service.com/resource'){ |response, request, result, &block| | |
if [301, 302, 307].include? response.code | |
response.follow_redirection(request, result, &block) | |
else | |
response.return!(request, result, &block) | |
end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment