Add `Authorization Bearer` hash to Net::HTTP post request (Ruby)

半世苍凉 提交于 2021-01-27 06:59:23

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/41032890/add-authorization-bearer-hash-to-nethttp-post-request-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!