OAuth 和 HTTParty

发布于 2024-09-13 04:35:37 字数 306 浏览 8 评论 0原文

是否可以将 OAuth 与 HTTParty 结合使用?我正在尝试执行 this API 调用,但是,与文档,它需要身份验证。

在你说“使用 Twitter 专用的 Gem”之前,请听我说完——我已经尝试过了。我尝试过 twitter、grackle 和无数其他的,但都不支持这个特定的 API 调用。所以,我转向了 HTTParty。

那么,如何将 OAuth 与 HTTParty 结合使用呢?

Is it possible to use OAuth with HTTParty? I'm trying to do this API call, but, contradictory to the documentation, it needs authentication.

Before you say "Use a Twitter-specific Gem", hear me out--I've tried. I've tried twitter, grackle, and countless others, but none support this specific API call. So, I've turned to HTTParty.

So, how could I use OAuth with HTTParty?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

世界和平 2024-09-20 04:35:37

我一直在使用 vanilla OAuth gem 来实现一些简单的 Twitter API 调用。我不需要一个重量级的 gem 来做所有事情,而且我已经在使用 OAuth,所以“自己动手”的方法似乎是合理的。我知道我没有提到 HTTParty,所​​以请不要为此责怪我。如果您已经在使用 OAuth gem,这可能对其他人有用,因为它了解简单的 Twitter OAuth 的本质。

如果它有帮助,这里是相关的代码(很抱歉在开始时混合了一些常量和其他变量/方法 - 这是从我的真实代码中提取它的最简单和最准确的方法):

#Set up the constants, etc required for Twitter OAuth
OAUTH_SITE = "https://api.twitter.com"
TOKEN_REQUEST_METHOD = :post
AUTHORIZATION_SCHEME = :header 

  def app_request_token_path 
    "/oauth/request_token"  
  end    
  def app_authorize_path 
    "/oauth/authorize"  
  end      
  def app_access_token_path        
    "/oauth/access_token"        
  end
  def consumer_key
    "your twitter API key"
  end
  def consumer_secret
    "your twitter API secret"
  end

  # Define the OAuth consumer
  def consumer meth=:post
    @consumer ||= OAuth::Consumer.new(consumer_key,consumer_secret, {
      :site => "#{OAUTH_SITE}",
      :request_token_path=>app_request_token_path,
      :authorize_path=>app_authorize_path,
      :access_token_path=>app_access_token_path,
      :http_method=>:post,
      :scheme=> :header,
      :body_hash => ''
    })
  end            

  # Essential parts of a generic OAuth request method
  def make_request url, method=:get, headers={}, content=''                  
    if method==:get
      res = @access_token.get(url, headers)
    elsif method==:post
      res = @access_token.post(url, content, headers)
    end

    if res.code.to_s=='200'
      jres = ActiveSupport::JSON.decode(res.body)
      if jres.nil?
        @last_status_text = @prev_error = "Unexpected error making an OAuth API call - response body is #{res.body}"
      end      
      return jres
    else
      @last_status_text = @prev_error = res if res.code.to_s!='200'
      return nil      
    end
  end

# Demonstrate the daily trends API call
# Note the use of memcache to ensure we don't break the rate-limiter
  def daily_trends

     url = "http://api.twitter.com/1/trends/daily.json"     
     @last_status_code = -1
     @last_status_success = false
     res = Rails.cache.fetch(url, :expires_in=> 5.minutes) do
       res = make_request(url, :get)          
       unless res
         @last_status_code = @prev_error.code.to_i
       end
       res
     end                 
     if res
         @last_status_code = 200
         @last_status_success = true
         @last_status_text = ""
     end
     return res
  end  

我希望这主要是在上下文中OAuth gem 的更广泛使用,可能对其他人有用。

I've been using the vanilla OAuth gem to implement a few simple Twitter API calls. I didn't need a heavyweight gem to do everything, and I was already using OAuth, so a 'roll-your-own' approach seemed reasonable. I know that I haven't mentioned HTTParty, so please don't ding me for that. This may be useful to others for the essence of easy Twitter OAuth if you're already using the OAuth gem.

In case it is helpful, here is the pertinent code (sorry about mixing some constants and other variables / methods at the start - it was the easiest and most accurate way to extract this from my real code):

#Set up the constants, etc required for Twitter OAuth
OAUTH_SITE = "https://api.twitter.com"
TOKEN_REQUEST_METHOD = :post
AUTHORIZATION_SCHEME = :header 

  def app_request_token_path 
    "/oauth/request_token"  
  end    
  def app_authorize_path 
    "/oauth/authorize"  
  end      
  def app_access_token_path        
    "/oauth/access_token"        
  end
  def consumer_key
    "your twitter API key"
  end
  def consumer_secret
    "your twitter API secret"
  end

  # Define the OAuth consumer
  def consumer meth=:post
    @consumer ||= OAuth::Consumer.new(consumer_key,consumer_secret, {
      :site => "#{OAUTH_SITE}",
      :request_token_path=>app_request_token_path,
      :authorize_path=>app_authorize_path,
      :access_token_path=>app_access_token_path,
      :http_method=>:post,
      :scheme=> :header,
      :body_hash => ''
    })
  end            

  # Essential parts of a generic OAuth request method
  def make_request url, method=:get, headers={}, content=''                  
    if method==:get
      res = @access_token.get(url, headers)
    elsif method==:post
      res = @access_token.post(url, content, headers)
    end

    if res.code.to_s=='200'
      jres = ActiveSupport::JSON.decode(res.body)
      if jres.nil?
        @last_status_text = @prev_error = "Unexpected error making an OAuth API call - response body is #{res.body}"
      end      
      return jres
    else
      @last_status_text = @prev_error = res if res.code.to_s!='200'
      return nil      
    end
  end

# Demonstrate the daily trends API call
# Note the use of memcache to ensure we don't break the rate-limiter
  def daily_trends

     url = "http://api.twitter.com/1/trends/daily.json"     
     @last_status_code = -1
     @last_status_success = false
     res = Rails.cache.fetch(url, :expires_in=> 5.minutes) do
       res = make_request(url, :get)          
       unless res
         @last_status_code = @prev_error.code.to_i
       end
       res
     end                 
     if res
         @last_status_code = 200
         @last_status_success = true
         @last_status_text = ""
     end
     return res
  end  

I hope this, largely in context of broader use of the OAuth gem, might be useful to others.

可是我不能没有你 2024-09-20 04:35:37

我不认为 HTTParty 支持 OAuth(虽然我不是 HTTParty 方面的专家,但对于我的口味来说,它太高级且太慢)。

我只需使用 OAuth gem 直接调用 Twitter 请求。 Twitter API 文档甚至有一个使用示例: https:// /dev.twitter.com/docs/auth/oauth/single-user-with-examples#ruby

I don't think that HTTParty supports OAuth (though I am no expert on HTTParty, it's way too high-level and slow for my taste).

I would just call the Twitter request directly using OAuth gem. Twitter API documentation even has an example of usage: https://dev.twitter.com/docs/auth/oauth/single-user-with-examples#ruby

挽梦忆笙歌 2024-09-20 04:35:37

我混合使用了 OAuth2 gem 来获取身份验证令牌,并使用 HTTParty 来使查询

client = OAuth2::Client.new(apiKey, apiSecret, 
                            :site => "https://SiteForAuthentication.com")
oauthResponse = client.password.get_token(username, password)
token = oauthResponse.token

queryAnswer = HTTParty.get('https://api.website.com/query/location', 
                            :query => {"token" => token})

在很长一段时间内并不完美,但到目前为止它似乎已经成功了

I used a mix of the OAuth2 gem to get the authentication token and HTTParty to make the query

client = OAuth2::Client.new(apiKey, apiSecret, 
                            :site => "https://SiteForAuthentication.com")
oauthResponse = client.password.get_token(username, password)
token = oauthResponse.token

queryAnswer = HTTParty.get('https://api.website.com/query/location', 
                            :query => {"token" => token})

Not perfect by a long way but it seems to have done the trick so far

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文