打开远程 URL 返回空字符串?
Posted
技术标签:
【中文标题】打开远程 URL 返回空字符串?【英文标题】:Open remote URL returns empty string? 【发布时间】:2014-03-24 08:16:03 【问题描述】:我正在使用以下代码 sn-p,它正在工作,从 Spotify oEmbed API 获取 JSON 响应。
我正在这样做:
response = JSON.parse(open("https://embed.spotify.com/oembed/?url=http://open.spotify.com/album/5Mxj65mCzxUjDkoqz7JXPJ").read)
但是现在,它停止工作了,因为:
2.0.0p247 :017 > open("https://embed.spotify.com/oembed/?url=http://open.spotify.com/album/5Mxj65mCzxUjDkoqz7JXPJ").read
=> ""
但是,使用 cURL,我得到:
$curl https://embed.spotify.com/oembed/\?url\=http://open.spotify.com/album/5Mxj65mCzxUjDkoqz7JXPJ
"provider_url":"https:\/\/www.spotify.com","version":"1.0","thumbnail_width":300,"height":380,"thumbnail_height":300,"title":"Illum Sphere - 13. Embryonic","width":300,"thumbnail_url":"https:\/\/d3rt1990lpmkn.cloudfront.net\/cover\/d4f5d8624752eeae3dc8bc3d58e2155d095181c1","provider_name":"Spotify","type":"rich","html":"<iframe src=\"https:\/\/embed.spotify.com\/?uri=spotify:album:5Mxj65mCzxUjDkoqz7JXPJ\" width=\"300\" height=\"380\" frameborder=\"0\" allowtransparency=\"true\"><\/iframe>"
有什么建议吗?
【问题讨论】:
【参考方案1】:尝试传递User-Agent
:
require 'open-uri'
puts open("https://embed.spotify.com/oembed/?url=http://open.spotify.com/album/5Mxj65mCzxUjDkoqz7JXPJ", "User-Agent" => "Ruby/#RUBY_VERSION").read
结果:
"provider_url":"https:\/\/www.spotify.com","version":"1.0","thumbnail_width":300,"height":380,"thumbnail_height":300,"title":"
Illum Sphere - 13. Embryonic","width":300,"thumbnail_url":"https:\/\/d3rt1990lpmkn.cloudfront.net\/cover\/d4f5d8624752eeae3dc8b
c3d58e2155d095181c1","provider_name":"Spotify","type":"rich","html":"<iframe src=\"https:\/\/embed.spotify.com\/?uri=spotify:al
bum:5Mxj65mCzxUjDkoqz7JXPJ\" width=\"300\" height=\"380\" frameborder=\"0\" allowtransparency=\"true\"><\/iframe>"
【讨论】:
谢谢!那行得通。但是你对这种行为有解释吗? 不完全确定。由于它之前工作过(如您所说),我只能假设他们现在正在执行某种类型的user-agent
验证(从 curl 您隐式发送一个,例如 User-Agent: curl/7.30.0
)。当然,这只是一个疯狂的猜测。
这是一个非常有效的猜测。在不识别您的代码的情况下向站点发出请求被认为是一种糟糕的形式,无论是爬取还是使用 API。给他们一些东西来识别您,以便他们在您的代码行为不端时与您联系;这胜过被完全禁止。以上是关于打开远程 URL 返回空字符串?的主要内容,如果未能解决你的问题,请参考以下文章
为啥 django page cms get_absolute_url 返回一个空字符串?
ASP.NET Core Url.Action 返回空字符串
ASP.NET WebForms:Request.GetFriendlyUrlFileVirtualPath() 返回空字符串