乐闻世界logo
搜索文章和话题

How to make a HTTP request using Ruby on Rails?

1个答案

1

In Ruby on Rails, making HTTP requests can be done using several different methods, with the most common being the standard library Net::HTTP and the popular gems httparty or rest-client. Below, I will cover the basic usage of each method.

Using Net::HTTP

Net::HTTP is part of Ruby's standard library and can be used without installing additional gems. It is a powerful and flexible library capable of handling various HTTP requests.

Example:

For example, to retrieve JSON data from an API:

ruby
require 'net/http' require 'uri' require 'json' uri = URI('http://api.example.com/data') response = Net::HTTP.get(uri) data = JSON.parse(response) puts data

In this example, we first specify the request URI, then use Net::HTTP.get to issue the request and receive the response. Finally, we parse the JSON data.

Using httparty

httparty is a Ruby gem that simplifies HTTP requests, resulting in more concise code.

First, add httparty to your project:

bash
gem install httparty

Then, use it as follows:

ruby
require 'httparty' require 'json' response = HTTParty.get('http://api.example.com/data') data = JSON.parse(response.body) puts data

The HTTParty.get method directly returns a response object, from which we can access the body property and parse it into JSON.

Using rest-client

rest-client is another widely used HTTP client gem that provides straightforward methods for making HTTP requests.

First, ensure the gem is installed:

bash
gem install rest-client

Usage example:

ruby
require 'rest-client' require 'json' response = RestClient.get('http://api.example.com/data') data = JSON.parse(response) puts data

Similar to httparty, RestClient.get returns a response object that can be directly parsed into JSON.

Summary

In Ruby on Rails, you can choose between the standard library Net::HTTP or more concise third-party gems like httparty or rest-client for making HTTP requests. The choice depends on your project requirements and personal or team preferences. Each method has its advantages: Net::HTTP offers great flexibility without extra dependencies, while httparty and rest-client excel at simplifying code.

2024年8月5日 01:57 回复

你的答案