Ruby RestClient.post用于登录表单

我正在尝试使用以下代码登录网站:

require 'rubygems' require 'nokogiri' require 'open-uri' require 'csv' require 'restclient' HEADERS_HASH = {"User-Agent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/534.57.5 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.4"} page = Nokogiri::HTML(open("http://example.com/login", HEADERS_HASH)) token = page.css("form.login_box div input")[0]['value'] login_resp = RestClient.post("https://example.com/session", {"authenticity_token" => token, "login" => 'username', "password" => 'password', "remember_me" => 1, 'commit' => 'Sign In'}) 

但是我收到以下错误:

 /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/abstract_response.rb:39:in `return!': 302 Found (RestClient::Found) from /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/request.rb:230:in `process_result' from /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/request.rb:178:in `block in transmit' from /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/1.9.1/net/http.rb:745:in `start' from /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/request.rb:172:in `transmit' from /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/request.rb:64:in `execute' from /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient/request.rb:33:in `execute' from /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/gems/1.9.1/gems/rest-client-1.6.7/lib/restclient.rb:72:in `post' from btw.rb:13:in `' 

我不确定这个错误告诉我的是什么? 任何建议?

这是表单代码:

  

你有一个302重定向来响应你的POST请求。 RestClient不会在POST上处理重定向,因此会抛出exception。 您需要在代码中处理此exception,以便您可以确定响应的内容或重定向的位置。

有关更多信息,请参阅此处的RestClient文档 。

你也可以使用这里描述的块forms ,它似乎不会抛出POST 302重定向的exception,并允许你直接在块内处理它:

 # Follow redirections for all request types and not only for get and head # # RFC : "If the 301, 302 or 307 status code is received in response to a # request other than GET or HEAD, the user agent MUST NOT automatically # redirect the request unless it can be confirmed by the user, since this # might change the conditions under which the request was issued." RestClient.get('http://my-rest-service.com/resource'){ |response, request, result, &block| if [301, 302, 307].include? response.code response.follow_redirection(request, result, &block) else response.return!(request, result, &block) end }