Ruby: Following redirects with the http gem ("httprb")

Posted . Visible to the public.

When making requests using the http gem you might want to automatically follow redirects to get the desired response. This is supported but not the default behavior.

You can do so by using the .follow method.
This follows redirects for the following status codes: 300, 301, 302, 303, 307, 308

response = HTTP.get('')
response.status # => 302
response.uri.to_s # => ""

response = HTTP.follow.get('')
response.status # => 200
response.uri.to_s # => ""

Limiting maximum amount of redirects

The .follow method also allows setting a maximum allowed amount of hops by settings the :max_hops option.The default is 5.
curl for example uses 30 as the default Show snapshot .

# would raise an error if there are more than 3 redirects
response = HTTP.follow(max_hops: 3).get('') 

Endless redirect loops

These are automatically checked for and an error will be raised if this occurs.

For more information see the httprb docs Show snapshot .

Maximilian Berger
Last edit
Felix Eschey
Source code in this card is licensed under the MIT License.
Posted by Maximilian Berger to makandra dev (2024-05-13 09:17)