带有Ruby的错误URI

问题描述 投票:4回答:1

我正在对Facebook API进行Oauth调用,以使自己获得access_token

def access_token
  token_uri = URI("https://graph.facebook.com/oauth/access_token?client_id=#{CLIENT_ID}&client_secret=#{CLIENT_SECRET}&grant_type=client_credentials")
  token_response = HTTParty.get(token_uri)
  Rails.logger.info(token_response)
  return token_response
end

我得到一个响应并生成一个access_token,假设它是

access_token=123456789|abcdefghijk

但是当我随后尝试使用此令牌时

def get_feed
  fb_access_token = access_token
 uri = URI("https://graph.facebook.com/#{VANDALS_ID}/posts/?#{fb_access_token}")

结束

我收到错误

URI::InvalidURIError: bad URI(is not URI?)

并且生成的uri在|处停止。即使管道后面还有更多字符可以完成我的access_key

https://graph.facebook.com/id-here/posts/?access_token=123456789|

如何获得我的URI中可用的完全访问令牌?

ruby-on-rails ruby facebook-graph-api uri
1个回答
7
投票

您收到错误的原因是|符号在正确的URI中不允许使用,因此在解析之前必须对其进行转义。 URI带有为您执行此操作的方法:

uri = URI(URI.escape "https://graph.facebook.com/#{VANDALS_ID}/posts/?#{fb_access_token}")
uri.to_s     #=> https://graph.facebook.com/id-here/posts/?access_token=123456789%7Cabcdefghijk

当请求URL时,服务器应自动对其进行解码,因此所有内容都应按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.