将 `Authorization Bearer` 哈希添加到 Net::HTTP post 请求 (Ruby)

问题描述 投票:0回答:2

如何使用

Authorization Bearer
Net::HTTP
添加到 POST 请求?

我只能在文档中找到“基本身份验证”的帮助。

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...
部分。

有人有这方面的经验吗?

ruby curl net-http
2个回答
12
投票

我认为您不能使用

post_form
方法添加自定义标头。可以用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)

0
投票

这是另一种风格:

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

url = 'http://localhost:8080/places'
token = 'eyJ0eXAiO...'
payload = [{'uuid': '0514b...', 'name': 'Athens'}]

uri = URI.parse(url)
request = Net::HTTP::Post.new(uri)
request.content_type = 'application/json'
request['Authorization'] = "Bearer #{token}"
request.body = payload.to_json
response = Net::HTTP.start(
  uri.host,
  uri.port,
  use_ssl: uri.scheme == 'https'
) do |http|
  http.request(request)
end

if response.is_a?(Net::HTTPSuccess)
  puts JSON.parse(response.body)
else
  puts "POST failed: #{response.code} - #{response.message}"
end
© www.soinside.com 2019 - 2024. All rights reserved.