2013-04-16 27 views
0

這裏是我的問題:回報率登錄到頁面,POST數據到遠程URL

我需要從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 ..因爲我沒有授權?我如何授權?

我也想我的運氣機械化寶石(以下 - 使用相同的「樣本」數據\乏)

#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.. 

回答

1

我覺得機械化寶石是你最好的選擇。

Here是一個示例,顯示如何使用機械化將文件發佈到閃爍。 也許你可以很容易地適應你的需求:

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