0

这是我的问题:

我需要将数据从 RoR 服务器发布到远程 PHP 服务器,到特定的 url,但在此之前我需要进行身份验证.. 任何帮助都非常感谢..

到目前为止我所做的..

#sample data
postparams ={'id'=>1, 'name'=>'Test', 'phone'=>'123123123'}
#url - is in form http://domain.com/some/somemore
#user - contains username
#pass - contains password

require "uri"
require "net/http"

uri = URI(url)
req = Net::HTTP::Post.new(uri.path)
req.set_form_data(postparams)

res = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(req)
end

case res
when Net::HTTPSuccess, Net::HTTPRedirection
 #all ok
else
  res.value
end

显然我得到 403 .. 因为我没有被授权?我如何授权?

我还用 mechanize gem 试试运气(下图 - 使用相同的“样本”数据\vars)

#when not logged in it renders login form
login_form = agent.get(url).forms.first
login_form.username = user
login_form.password = pass

# submit login form
agent.submit(login_form, login_form.buttons.first)

#not sure how to submit to url..
#note that accessing url will not render the from 
#(I can't access it as I did with login form) - I simply need to post postparams
#to this url... and get the response code..
4

2 回答 2

1

我认为机械化宝石是您的最佳选择。

是一个示例,展示了如何使用 mechanize 将文件发布到闪烁。也许您可以轻松适应您的需求:

require 'rubygems'
require 'mechanize'

abort "#{$0} login passwd filename" if (ARGV.size != 3)

a = Mechanize.new { |agent|
  # Flickr refreshes after login
  agent.follow_meta_refresh = true
}

a.get('http://flickr.com/') do |home_page|
  signin_page = a.click(home_page.link_with(:text => /Sign In/))

  my_page = signin_page.form_with(:name => 'login_form') do |form|
    form.login  = ARGV[0]
    form.passwd = ARGV[1]
  end.submit

  # Click the upload link
  upload_page = a.click(my_page.link_with(:text => /Upload/))

  # We want the basic upload page.
  upload_page = a.click(upload_page.link_with(:text => /basic Uploader/))

  # Upload the file
  upload_page.form_with(:method => 'POST') do |upload_form|
    upload_form.file_uploads.first.file_name = ARGV[2]
  end.submit
end
于 2013-04-16T20:56:56.987 回答
0

我强烈建议使用 ruby​​ rest-client gem。

于 2013-04-16T13:17:44.403 回答