Ruby - Send Get Request with Headers

Ruby - Send GET request with headers

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, use_ssl: uri.scheme == 'https') { |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

Ruby https POST with headers

The problem it was a json. This solve my problem. Anyway, my question was not clear, so the bounty goes to Juri

require 'uri'
require 'net/http'
require 'net/https'
require 'json'

@toSend = {
"date" => "2012-07-02",
"aaaa" => "bbbbb",
"cccc" => "dddd"
}.to_json

uri = URI.parse("https:/...")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
req['foo'] = 'bar'
req.body = "[ #{@toSend} ]"
res = https.request(req)
puts "Response #{res.code} #{res.message}: #{res.body}"

Sending custom HTTP headers with Ruby

Finally figured it out. When setting up an HTTP request, using the 'https' scheme does not automatically enable TLS/SSL. You must do this explicitly before the request starts. Here's my updated version:

#!/usr/bin/env ruby -w
# frozen_string_literal: true

require 'fileutils'
require 'net/http'
require 'time'

cached_response = 'index.html' # Added
FileUtils.touch cached_response unless File.exist? cached_response # Added
uri = URI("https://www.apple.com/#{cached_response}") # Changed
file = File.stat cached_response

req = Net::HTTP::Get.new(uri)
req['If-Modified-Since'] = file.mtime.rfc2822

http = Net::HTTP.new(uri.hostname, uri.port) # Added
http.use_ssl = uri.scheme == 'https' # Added
res = http.start { |h| h.request(req) } # Changed

if res.is_a?(Net::HTTPSuccess)
File.open cached_response, 'w' do |io|
io.write res.body
end
end

how do I include a header in an http request in ruby

get_response is a shorthand for making a request, when you need more control - do a full request yourself.

There's an example in ruby standard library here:

uri = URI.parse("http://www.ncdc.noaa.gov/cdo-web/api/v2/datasets/")
req = Net::HTTP::Get.new(uri)
req['token'] = 'fjhKJFSDHKJHjfgsdfdsljh'

res = Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(req)
}

How to add `headers` to my get `request`.

Use request.env to set the header

it "can find an account" do 
request.env['AUTH_TOKEN'] = "token"
get "/accounts/#{@acc.id}/"
end

Is there a way to pass parameters and headers using Net::HTTP in Ruby?

I am not sure if it's a solution for you but I've rewritten your code to use HTTParty gem instead of net/http. In my opinion it's much easier to use this gem.
As a result, I've got {"code":-2014,"msg":"API-key format invalid."} which I think is a proper response as far I don't have API key for Binance.

require 'json'
require 'uri'
require 'httparty'
require 'openssl'

def params_with_signature(params, secret)
params = params.reject { |_k, v| v.nil? }
query_string = URI.encode_www_form(params)
signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret, query_string)
params.merge(signature: signature)
end

params = {
symbol: 'BNBBTC',
side: 'BUY',
type: 'MARKET',
timeInForce: 'GTC',
quantity: 1,
recvWindow: 5000,
timestamp: Time.now.to_i * 1000
}

BASE_URL = 'https://api.binance.com'
api_key = ''
api_secret = ''

uri = URI("#{BASE_URL}/api/v3/order")

headers = {
'X-MBX-APIKEY': api_key,
'Content-Type': 'text/json'
}

response = HTTParty.post(uri, headers: headers, body: params_with_signature(params, api_secret))

puts response.body

Let me know if it helped you :)

For Net/Http soution you may look here: https://stackoverflow.com/questions/1252210/parametrized-get-request-in-ruby



Related Topics



Leave a reply



Submit