【问题标题】:Instagram embed code from url (Rails)Instagram 从 url 嵌入代码 (Rails)
【发布时间】:2016-02-04 10:30:36
【问题描述】:

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

我找到了这个参考: 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 进行身份验证。

有办法吗?

【问题讨论】:

  • 所以它会重定向?响应应该返回重定向位置,你会得到什么你跟随重定向?
  • 响应中没有重定向url

标签: ruby-on-rails rubygems instagram instagram-api


【解决方案1】:

您可以通过soulim 使用oembed gem。获取嵌入代码的好方法

instagram 是这样的

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

gem 'oembed'

下一个

bundle install

创建一个帮助类

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"]

【讨论】:

【解决方案2】:

使用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

所以只需按照重定向。

【讨论】:

  • 看起来他们还没有完成 api 的实现,很奇怪你会被重定向到最终给你响应的初始 url。
  • @guyaloni 是的,非常奇怪。
猜你喜欢
  • 2013-07-21
  • 1970-01-01
  • 2018-07-27
  • 1970-01-01
  • 2010-12-30
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多