Ruby - Send GET request with headers

前端 未结 2 616
清酒与你
清酒与你 2020-12-17 20:43

I am trying to use ruby with a website\'s api. The instructions are to send a GET request with a header. These are the instructions from the website and the example php code

相关标签:
2条回答
  • 2020-12-17 21:00

    Using net/http as suggested by the question.

    References:

    • Net::HTTP https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html
    • Net::HTTP::get https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#method-c-get
    • Setting headers: https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Setting+Headers
    • Net::HTTP::Get https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP/Get.html
    • Net::HTTPGenericRequest https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTPGenericRequest.html and Net::HTTPHeader https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTPHeader.html (for methods that you can call on Net::HTTP::Get)

    So, for example:

    require 'net/http'    
    
    uri = URI("http://www.ruby-lang.org")
    req = Net::HTTP::Get.new(uri)
    req['some_header'] = "some_val"
    
    res = Net::HTTP.start(uri.hostname, uri.port) {|http|
      http.request(req)
    }
    
    puts res.body # <!DOCTYPE html> ... </html> => nil
    

    Note: if your response has HTTP result state 301 (Moved permanently), see Ruby Net::HTTP - following 301 redirects

    0 讨论(0)
  • 2020-12-17 21:17

    Install httparty gem, it makes requests way easier, then in your script

    require 'httparty'
    
    url = 'http://someexample.com'
    headers = {
      key1: 'value1',
      key2: 'value2'
    }
    
    response = HTTParty.get(url, headers: headers)
    puts response.body
    

    then run your .rb file..

    0 讨论(0)
提交回复
热议问题