Ruby on rails 相当于rails模型或控制器中的cURL Post请求调用

Ruby on rails 相当于rails模型或控制器中的cURL Post请求调用,ruby-on-rails,box-api,Ruby On Rails,Box Api,当我从终端调用它时,下面的代码行工作正常。我想在我的Rails应用程序中运行它的等效程序来刷新我的access\u令牌字段(请参阅): 假设我有所有可用的参数,我将如何从模型或控制器发布此请求?Net::HTTP.post_form(URI.parse(“https://api.box.com/oauth2/token?grant_type=refresh_token&refresh_token=#{valid_refresh_token}和client_id={your_client_id}和

当我从终端调用它时,下面的代码行工作正常。我想在我的Rails应用程序中运行它的等效程序来刷新我的access\u令牌字段(请参阅):

假设我有所有可用的参数,我将如何从模型或控制器发布此请求?

Net::HTTP.post_form(URI.parse(“https://api.box.com/oauth2/token?grant_type=refresh_token&refresh_token=#{valid_refresh_token}和client_id={your_client_id}和client_secret={your_client_secret}”))

我最终在身份验证模型中实现了以下代码,以获得一个刷新的Box OAuth令牌。这样我就可以像
User.authentication.find\u by\u provider('box')。刷新如果过期(我每次通过
令牌
方法调用Box API时都会进行检查)


这将返回
参数错误:参数数目错误(1代表2)
。我还尝试了
Net::HTTP.post_form(uri,params)
(uri=
uri.parse()https://api.box.com/oauth2/token“
和params是一个包含我的键和值的散列),它返回
curl https://api.box.com/oauth2/token \
-d 'grant_type=refresh_token&refresh_token={valid refresh token}&client_id={your_client_id}&client_secret={your_client_secret}' \
-X POST
  require 'uri'
  require 'net/http'

  def refresh!
    case self.provider
    when 'box'
      url = "https://api.box.com/oauth2/token"
      uri = URI(url)
      params = {}
      params["grant_type"] = "refresh_token"
      params["refresh_token"] = self.refresh_token
      params["client_id"] = APP_CONFIG['box_client_id']
      params["client_secret"] = APP_CONFIG['box_client_secret']
      res = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
               req = Net::HTTP::Post.new(uri.path)
               req.set_form_data(params)
               response = http.request(req)
            end
      res_json = JSON.parse(res.body)
      self.refresh_token = res_json["refresh_token"]
      self.oauth_token = res_json["access_token"]
      self.expires_at = Time.now.to_i + res_json["expires_in"].to_i
      self.save      
    end
  end

  def fresh_token
    case self.provider
    when 'box'
      self.refresh! if self.is_expired? && self.is_refreshable?
      self.oauth_token
    else
      self.oauth_token
    end
  end


  def is_refreshable?
    case self.provider
    when 'box'
      Time.now < self.updated_at + 14.days ? true : false
    else
      nil
    end
  end


  def is_expired?
    case self.provider
    when 'box'
      Time.now.to_i > self.expires_at ? true : false
    else
      false      
    end
  end
  def profile
    token = self.fresh_token

    case self.provider
    when 'box'
      profile = JSON.parse(open("https://api.box.com/2.0/users/me?access_token=#{token}").read)
    end
  end