用密钥和秘密发送请求

时间:2014-09-29 10:50:40

标签: ruby json get

我打算用net / http发送GET请求:

require 'net/http'
response = Net::HTTP.get_response("example.com", "/whoareyou.json")

但我需要在网址中包含密钥和密钥。我试着这样做:

require 'net/http'
response = Net::HTTP.get_response("<key>:<secret>@example.com", "/whoareyou.json")

但不幸的是我得到了令人讨厌的错误:

/usr/lib/ruby/1.9.1/net/http.rb:762:in `initialize': getaddrinfo: Name or service not known (SocketError)

1 个答案:

答案 0 :(得分:1)

Net :: HTTP不支持从URL进行基本身份验证。你需要调用req.basic_auth'user','pass'

http://ruby-doc.org/stdlib-2.1.3/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Basic+Authentication

我建议使用真正简化大多数HTTP内容的HTTP Party gem(https://github.com/jnunemaker/httparty),例如,请参阅此答案,了解基本身份验证如何与HTTP方一起使用:How to use basic authentication with httparty in a Rails app?

在你的例子中:

res = HTTParty.get("http:example.com/whoareyou.json", :basic_auth=> {:username =>user, :password => password})
                 :basic_auth => auth)