Надсилання HTTP-запиту

Ruby:
Надсилання HTTP-запиту

How to:

Як це зробити:

Ruby’s standard library, Net::HTTP, is simple to use for sending requests:

require 'net/http'
require 'uri'

uri = URI('https://api.example.com/items')
response = Net::HTTP.get(uri)

puts response

Sample output:

[{"id":1,"name":"Apple"},{"id":2,"name":"Orange"}]

Post request with form data:

require 'net/http'
require 'uri'

uri = URI('https://api.example.com/items')
request = Net::HTTP::Post.new(uri)
request.set_form_data({'name' => 'Banana'})

response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
  http.request(request)
end

puts response.body

Assuming the API acknowledges the POST request:

{"id":3,"name":"Banana","status":"created"}

Deep Dive

Поглиблений Аналіз:

Ruby’s Net::HTTP module has been around since the 1.x days, constantly evolving. It became friendlier with the introduction of methods like Net::HTTP.get and wrappers like OpenURI. It’s basic, but it works.

Alternatives? You bet. Many prefer gems like ‘httparty’ or ‘rest-client’ for syntactic sugar. They’re more intuitive and feature-packed.

Implementation details? Using Net::HTTP.start helps manage connections more effectively. SSL? Set use_ssl: true and always verify certificates to avoid security risks.

See Also

Дивіться Також: