mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Check If A URL Resolves To 200 as a Ruby TIL
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||
|
||||
_1293 TILs and counting..._
|
||||
_1294 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -1013,6 +1013,7 @@ _1293 TILs and counting..._
|
||||
- [Build HTTP And HTTPS URLs](ruby/build-http-and-https-urls.md)
|
||||
- [Chaining Multiple RSpec Change Matchers](ruby/chaining-multiple-rspec-change-matchers.md)
|
||||
- [Check For Any Overlaps In List Of Ranges](ruby/check-for-any-overlaps-in-list-of-ranges.md)
|
||||
- [Check If A URL Resolves To 200](ruby/check-if-a-url-resolves-to-200.md)
|
||||
- [Check If An Object Includes A Module](ruby/check-if-an-object-includes-a-module.md)
|
||||
- [Check Return Status Of Running A Shell Command](ruby/check-return-status-of-running-a-shell-command.md)
|
||||
- [Click On Text With Capybara](ruby/click-on-text-with-capybara.md)
|
||||
|
||||
29
ruby/check-if-a-url-resolves-to-200.md
Normal file
29
ruby/check-if-a-url-resolves-to-200.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Check If A URL Resolves To 200
|
||||
|
||||
Ruby's built-in [`Net::HTTP`
|
||||
library](https://ruby-doc.org/stdlib-2.7.0/libdoc/net/http/rdoc/Net/HTTP.html)
|
||||
allows us to make different kinds of HTTP requests. We can use it to make a
|
||||
`HEAD` request which will request the status of a URL without actually fetching
|
||||
its contents.
|
||||
|
||||
We can work directly with `Net::HTTP` using strings, but I find it is easier
|
||||
and less error-prone to get help from the `URI` class.
|
||||
|
||||
To make a `#head` request, we first need to establish a connection to the host
|
||||
with [the `#start`
|
||||
method](https://ruby-doc.org/stdlib-2.7.0/libdoc/net/http/rdoc/Net/HTTP.html#method-i-start).
|
||||
Then we can initiate our request from that connection object.
|
||||
|
||||
```ruby
|
||||
url = 'https://my.app.com/path/to/video.mp4'
|
||||
uri = URI(url)
|
||||
conn = Net::HTTP.start(uri.host, uri.port, use_ssl: true)
|
||||
resp = conn.head(uri.path)
|
||||
|
||||
resp.code
|
||||
#=> "200"
|
||||
```
|
||||
|
||||
We initiate the connection with the host and port of our URL. Then request the
|
||||
`HEAD` response for the path of our URL. If we are working with an `https` URL,
|
||||
we need to indicate that with `use_ssl: true` in the `#start` method options.
|
||||
Reference in New Issue
Block a user