How can I add Authorization Bearer
to a POST request with Net::HTTP
?
I can only find help for "basic authentication" in the documentation.
req.basic_auth 'user', 'pass'
Source: https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html#class-Net::HTTP-label-Basic+Authentication
I'm trying to replicate a curl that would look like:
> curl 'http://localhost:8080/places' -d '{"_json":[{"uuid":"0514b...",
> "name":"Athens"}]}' -X POST -H 'Content-Type: application/json' -H
> 'Authorization: Bearer eyJ0eXAiO...'
Currently I've gotten to:
require 'net/http'
require 'net/https'
require 'uri'
uri = URI('http://localhost:8080/places')
res = Net::HTTP.post_form(uri, '_json' => [{'uuid': '0514b...', 'name':'Athens'}])
But I'm having trouble figuring out how to add the Authentication: Bearer...
part.
Does anyone have experience with this?
I dont think you can add custom headers with the post_form
method. You can add it with post method. Try the code below:
uri = URI("http://localhost:8080/places")
params = [{'uuid': '0514b...', 'name':'Athens'}]
headers = {
'Authorization'=>'Bearer foobar',
'Content-Type' =>'application/json',
'Accept'=>'application/json'
}
http = Net::HTTP.new(uri.host, uri.port)
response = http.post(uri.path, params.to_json, headers)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With