简体   繁体   中英

Ruby on Rails curl POST request with user authentication

I'm trying to do a curl post request to a REST API in rails. The cURL request I'm trying to do is:

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

I've seen the many examples of using net/http for API POST requests in rails, but I never found an example that adds -u to the request. How do I do this?

We can perform a Basic Authentication by using the method 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

Figured it out. For people with a similar issue:

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM