Ruby - Send GET request with headers

前端 未结 2 617
清酒与你
清酒与你 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 #  ...  => nil
    

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

提交回复
热议问题