【问题标题】:Add `Authorization Bearer` hash to Net::HTTP post request (Ruby)将 `Authorization Bearer` 哈希添加到 Net::HTTP 发布请求 (Ruby)
【发布时间】:2017-04-23 07:22:27
【问题描述】:

如何将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


    【解决方案1】:

    我认为您不能使用 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)
    

    【讨论】:

    • 不要把冒号放在Bearer之后
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 2012-12-15
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    相关资源
    最近更新 更多