使用Ruby Httparty和Json登录失败

时间:2013-11-28 21:31:18

标签: ruby-on-rails ruby json httparty

我试图登录到具有以下API的网站: 发布https://www.Thesite.com/Account/LogOn 发布JSON data:{UserName:xxx,Pasword:xxx,SecondFactor:[optional]} 保存CookieContainer& header["SecretKey"]传递下一个电话,否则你会得到409冲突 我编写了以下Ruby脚本,但响应是:输入用户名和密码 怎么了?

!/usr/bin/env ruby
require "rubygems"
require "httparty"

include HTTParty 

class TheSite   
  base_uri 'https://www.Thesite.com'
  def initialize(u, p)
    @data = {:UserName => u, :Pasword => p}.to_json
    response = self.class.get('/Account/LogOn')
    response = self.class.post(
      '/Account/LogOn',
       :data => @data,
       :headers=>{'SecretKey'=>response.headers['Set-Cookie']})
       @cookie = response.request.options[:headers]['cookie']
    puts response
  end
end

thesite = Thesite.new('myuser', 'mypassword')

1 个答案:

答案 0 :(得分:0)

这里有一点不正确:

  • 您不需要JSONify数据,但您需要设置正确的JSON标头。很多人这样做都不用担心。
  • 整个cookie都是在请求之后发生的,而不是在它中。
  • 这里有一些丢失的括号膨胀。

这是一个有效的例子:

!/usr/bin/env ruby
require "rubygems"
require "httparty"

include HTTParty 

class TheSite   
  base_uri 'https://www.Thesite.com'
  def initialize(u, p)
    @data = {
      :UserName => u,
      :Password => p
    } 
    res = self.class.post('Account/LogOn', 
                          :body => @data, 
                          :options => {
                            :headers => { 
                              'ContentType' => 'application/json', 
                              'Accept'      => 'application/json',
                              'SecretKey'   => res.headers['Set-Cookie']                          
                            }
                          }
                         )
    if res.code == 200
      @cookie = res.request.options[:headers]['Cookie']
      # do stuff
    end
  end
end