将 `Authorization Bearer` 哈希添加到 Net::HTTP post 请求 (Ruby)
Add `Authorization Bearer` hash to Net::HTTP post request (Ruby)
如何将 Authorization Bearer
添加到带有 Net::HTTP
的 POST 请求?
我只能在文档中找到 "basic authentication" 的帮助。
req.basic_auth 'user', 'pass'
来源:https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html#class-Net::HTTP-label-Basic+Authentication
我正在尝试复制一个看起来像这样的卷曲:
> curl 'http://localhost:8080/places' -d '{"_json":[{"uuid":"0514b...",
> "name":"Athens"}]}' -X POST -H 'Content-Type: application/json' -H
> 'Authorization: Bearer eyJ0eXAiO...'
目前我已经:
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'}])
但我不知道如何添加 Authentication: Bearer...
部分。
有人有这方面的经验吗?
我认为您不能使用 post_form
方法添加自定义 headers。您可以使用 post 方法添加它。试试下面的代码:
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)
如何将 Authorization Bearer
添加到带有 Net::HTTP
的 POST 请求?
我只能在文档中找到 "basic authentication" 的帮助。
req.basic_auth 'user', 'pass'
来源:https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html#class-Net::HTTP-label-Basic+Authentication
我正在尝试复制一个看起来像这样的卷曲:
> curl 'http://localhost:8080/places' -d '{"_json":[{"uuid":"0514b...",
> "name":"Athens"}]}' -X POST -H 'Content-Type: application/json' -H
> 'Authorization: Bearer eyJ0eXAiO...'
目前我已经:
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'}])
但我不知道如何添加 Authentication: Bearer...
部分。
有人有这方面的经验吗?
我认为您不能使用 post_form
方法添加自定义 headers。您可以使用 post 方法添加它。试试下面的代码:
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)