来自 url (Rails) 的 Instagram 嵌入代码

Instagram embed code from url (Rails)

在我的应用程序中,我想允许用户引入一个 url 的 instagram,然后自动检索它的嵌入代码。

我找到了这个参考资料: https://www.instagram.com/developer/embedding/#oembed

当我在我的 Chrome 浏览器中尝试给定的示例 (https://api.instagram.com/oembed?url=http://instagr.am/p/fA9uwTtkSN) 时,我得到了 json 和我正在寻找的代码。

但是,如果我从 rails 控制台尝试此操作:

Net::HTTP.get_response(URI("https://api.instagram.com/oembed?url=http://instagr.am/p/fA9uwTtkSN"))

我明白了:

#<Net::HTTPMovedPermanently 301 MOVED PERMANENTLY readbody=true> 

我看到 instagram 有一个新的 API,但我不想让用户从 instagram 进行身份验证。

有办法吗?

使用 docs

def fetch(uri_str, limit = 10)
  # You should choose a better exception.
  raise ArgumentError, 'too many HTTP redirects' if limit == 0

  response = Net::HTTP.get_response(URI(uri_str))

  case response
  when Net::HTTPSuccess then
    response
  when Net::HTTPRedirection then
    location = response['location']
    warn "redirected to #{location}"
    fetch(location, limit - 1)
  else
    response.value
  end
end

str = "https://api.instagram.com/oembed?url=http://instagr.am/p/fA9uwTtkSN"
response = fetch(str)
redirected to https://api.instagram.com/publicapi/oembed/?url=http://instagr.am/p/fA9uwTtkSN
redirected to https://www.instagram.com/publicapi/oembed/?url=http://instagr.am/p/fA9uwTtkSN
redirected to https://api.instagram.com/oembed/?url=http://instagr.am/p/fA9uwTtkSN
=> #<Net::HTTPOK 200 OK readbody=true>

response.body
=> # JSON response

所以只要按照重定向。

您可以使用 oembed gem by soulim。获得嵌入代码的好方法

在 Instagram 的情况下,它是这样的

在您的 gem 文件中包含以下行

gem 'oembed'

下一个

bundle install

创建助手class

class InstaApi
  include Oembed::Client

  def endpoint_uri
    'http://api.instagram.com/oembed'
  end
end

现在您可以使用

instClient = InstaApi.new
info = instClient.fetch('http://instagr.am/p/BUG/')

获取您的嵌入代码

embed_code = info["html"]