【问题标题】:Ruby on Rails curl POST request with user authentication带有用户身份验证的 Ruby on Rails curl POST 请求
【发布时间】:2016-11-24 01:46:56
【问题描述】:

我正在尝试向 Rails 中的 REST API 发出 curl 发布请求。我正在尝试执行的 cURL 请求是:

$ curl https://api.intercom.io/events \
-X POST \
-u pi3243fa:da39a3ee5e6b4b0d3255bfef95601890afd80709 \
-H "Content-Type: application/json" 
-d' {   "event_name" : "invited-friend",   
"created_at": 1391691571,   "user_id" : "314159" }'

我已经看到了许多在 rails 中使用 net/http 进行 API POST 请求的示例,但我从未找到将 -u 添加到请求的示例。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails curl


    【解决方案1】:

    我们可以使用basic_auth方法来执行Basic Authentication

    uri = URI('http://example.com/index.html?key=value')
    
    req = Net::HTTP::Get.new(uri)
    req.basic_auth 'user', 'pass'
    
    res = Net::HTTP.start(uri.hostname, uri.port) {|http|
      http.request(req)
    }
    puts res.body
    

    【讨论】:

    • 我需要做一个 POST 请求,如何将它与这段代码结合起来?
    【解决方案2】:

    想通了。对于有类似问题的人:

        data = {"event_name" => "invited-friend",   
    "created_at" => 1391691571,   "user_id" => "314159" }
        uri = URI("https://api.intercom.io/events")
        header = {"Content-Type" => "application/json"}
        https = Net::HTTP.new(uri.host,uri.port)
        https.use_ssl = true
        req = Net::HTTP::Post.new(uri.path, header)
        req.basic_auth 'pi3243fa:da39a3ee5e6b4b0d3255bfef95601890afd80709', ''
        req.body = data.to_json
        res = https.request(req)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-01
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      相关资源
      最近更新 更多