ruby - 如何在 Ruby 中检查图像是否可热链接
问题描述
使用 Ruby,我想检查图像以查看它是否可热链接。我的代码在很多情况下都有效,但有时却无效。
代码:
class Hotlinkable
def self.is_hotlinkable? url
return if url.blank?
begin
res = get_response_with_redirect URI.parse(url)
res.code == '200'
rescue => e
puts e.inspect
false
end
end
def self.get_response_with_redirect(uri)
r = Net::HTTP.get_response(uri)
if r.code == "301"
r = Net::HTTP.get_response(URI.parse(r.header['location']))
end
r
end
end
例如,此图像在运行上述代码时返回 403: https ://searchengineland.com/figz/wp-content/seloads/2019/08/IMG_20190808_104849.jpg
但是当我把它放在图像标签中时,它加载得很好。
知道为什么上面的代码返回 403 吗?
解决方案
这里发生了很多事情。首先,您不提供任何请求标头。这样,服务器可以判断请求不是来自浏览器并以 403 响应。添加任何用户代理可以解决问题。但是,为了获得最佳结果,请检查浏览器发送的标头并复制所有标头。
下一个是处理 SSL。您需要告诉 Net::HTTP 对 https 请求使用 SSL。
这是用于获取响应的更新脚本:
uri = URI.parse("https://searchengineland.com/figz/wp-content/seloads/2019/08/IMG_20190808_104849.jpg")
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
request = Net::HTTP::Get.new(uri.request_uri)
request["User-Agent"] = "curl/7.58.0"
response = http.request(request)
推荐阅读
- javascript - 更改任何文本输入时函数运行
- php - 如何使用select2自动填充jquery ajax
- laravel - “调用未定义的关系 [latest_posts]”为每个父级获取 N 个相关模型时出错
- oracle12c - Pentaho 数据集成到 Oracle - 长错误消息
- html - Angular (Typescript): How can I set option of selected to 'selected' if two-way binded?
- angular - Angular6:自定义组件上的输入绑定没有正确更新
- python-3.x - 如何在scrapy中按顺序导出标签的文本
- java - org.springframework.beans.factory.UnsatisfiedDependencyException,org.springframework.beans.factory.NoSuchBeanDefinitionException
- node.js - Express/Parse - 无法得到回复
- c# - 有没有办法将“抛出新的异常()”挤压到一个对象中?