Net::HTTP ポストリクエストにハッシュを追加 (Ruby)
概要
Net::HTTP を使用して POST リクエストに Authorization Bearer を追加するにはどうすればよいですか?
ドキュメントには「基本認証」に関するヘルプしか見つかりません。
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 メソッドを使用してカスタムヘッダーを追加できるとは思いません。 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)