2016-11-24 101 views
0

我正在尝试在rails中对REST API执行curl post请求。我试图做卷曲的要求是:Ruby on Rails用用户认证curl POST请求

$ 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" }' 

我见过使用net/HTTP在轨API POST请求的例子很多,但我从来没有发现,增加-u的请求的示例。我该怎么做呢?

回答

0

我们可以利用该方法basic_auth

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 
+0

我需要做一个POST请求,我该如何结合这个代码? –

0

想通了执行Basic Authentication。对于有类似问题的人:

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)