How to Use HTTPClient Gem

09/23/2021

Contents

In this article, you will learn how to use HTTPClient gem.

Using HTTPClient gem

HTTPClient is a popular Ruby gem for making HTTP requests. It provides an easy-to-use API that allows developers to send requests and receive responses in a straightforward manner.

To use HTTPClient in your Ruby project, you’ll first need to install the gem. You can do this by running the following command in your terminal:

gem install httpclient

Once the gem is installed, you can start using it in your code. Here’s an example of how to use HTTPClient to make a GET request:

require 'httpclient'

client = HTTPClient.new
response = client.get('https://www.example.com')
puts response.body

In this example, we first require the HTTPClient gem, create a new instance of the HTTPClient class, and then use the get method to make a GET request to https://www.example.com. The response from the server is then stored in the response variable, and the body of the response is printed to the console using puts.

HTTPClient also supports other HTTP methods, such as POST, PUT, and DELETE. Here’s an example of how to use HTTPClient to make a POST request:

require 'httpclient'

client = HTTPClient.new
response = client.post('https://www.example.com', { name: 'John', age: 30 })
puts response.body

In this example, we use the post method to make a POST request to https://www.example.com, passing in a hash of parameters in the second argument. The response from the server is then stored in the response variable, and the body of the response is printed to the console using puts.

HTTPClient also supports various options, such as setting headers, timeouts, and SSL verification. Here’s an example of how to use options with HTTPClient:

require 'httpclient'

client = HTTPClient.new
client.set_cookie_store('/path/to/cookie.store')
client.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_PEER
response = client.get('https://www.example.com', { 'User-Agent' => 'MyApp/1.0' }, timeout: 10)
puts response.body

In this example, we use the set_cookie_store method to set the path to the cookie store file, the ssl_config method to set SSL verification to VERIFY_PEER, and the get method to make a GET request with a custom User-Agent header and a timeout of 10 seconds. The response from the server is then stored in the response variable, and the body of the response is printed to the console using puts.