How to make an HTTP request in Ruby?

0

How do I make an HTTP request in Ruby? I need to implement an API, and for this it is necessary to make a REST request for such a URL, how do I POST such a request?

    
asked by anonymous 22.12.2017 / 19:24

2 answers

1

It is available in the ruby documentation DOC , the example below

require 'net/http'

uri = URI('http://www.example.com/search.cgi')
res = Net::HTTP.post_form(uri, 'q' => ['ruby', 'perl'], 'max' => '50')
puts res.body
    
22.12.2017 / 19:31
0

The HTTP (http.rb) gem makes this work easier. To install, simply add to your Gemfile:

gem "http"

and run bundle install in the shell.

require 'http'
response = HTTP.post("https://api.test/post", :params => {:id => 5})
response.body # retorna um objeto representando a resposta
response.code # retorna o código HTTP da resposta, e.g. 404, 500, 200

If you need authentication, just:

HTTP.basic_auth(:user => "user", :pass => "pass")
  .get("https://example.com")

or if you want to pass the authorization "raw":

HTTP.auth("Bearer VGhlIEhUVFAgR2VtLCBST0NLUw")
  .get("https://example.com")
    
27.12.2017 / 04:24