我在这方面遇到了很多困难 - 似乎有几段代码可以放在一起我似乎无法拼凑在一起。我只是尝试POST键/值对,但获得Connection refused - connect(2) (Errno::ECONNREFUSED)
。救命啊!
require 'net/http'
require 'net/https'
require 'uri'
@http = Net::HTTP.new('https://my.url.com/path', 443)
@http.use_ssl = true
@http.start() { |http|
req = Net::HTTP.post_form(
URI.parse('https:///my.url.com/path'),
{'key1' => 'value1', 'key2' => 'value2'}
)
req.basic_auth 'username', 'password'
response = http.request(req)
puts response.body
}
答案 0 :(得分:18)
HTTP#post_form将直接执行,忽略您的其他设置。试试这个:
require 'net/http'
require 'uri'
url = URI.parse('https://my.url.com/path')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'user', 'pass'
req.use_ssl = true
req.form_data({'key1' => 'val1', 'key2' => 'val2'})
resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
puts resp
您可能会遇到服务器证书的问题。有关如何获取/配置它们的说明,请参阅我的其他post。
答案 1 :(得分:7)
在我搜索解决方案时发现了这个问题,并且只是为了清楚浮雕'代码是不起作用的。我工作的是这个(在更大的Sinatra应用程序中):
require 'net/http'
require 'net/https'
require 'uri'
set :api_username, 'usr'
set :api_passwor, 'pswd'
def do_auth_check params
puts params.inspect
url = URI.parse("https://my_auth_site.com:443/authenticate")
req = Net::HTTP::Post.new(url.path)
req.basic_auth options.api_username, options.api_password
req.set_form_data({'username' => params[:name], 'password' => params[:pass]})
sock = Net::HTTP.new(url.host, url.port)
sock.use_ssl = true
res = sock.start {|http| http.request(req) }
# you're on your own down here to identify success/failure, but for me 2xx/3xx was ok and 401/404/500/etc would be failure
return true if res.code.to_i < 400
return "Error logging in"
end