首页 > 解决方案 > 如何在 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 吗?

标签: rubyhotlinking

解决方案


这里发生了很多事情。首先,您不提供任何请求标头。这样,服务器可以判断请求不是来自浏览器并以 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)

推荐阅读