Ruby - 如果 url 是重定向,如何下载文件?

标签 ruby http soundcloud response.redirect http-redirect

如果 url 是重定向,Ruby 如何下载文件?

我正在尝试下载这个 url:

soundcloud.com/stereo-f---/cohete-amigo/download

重定向是这样的:

[ec-media.soundcloud.com/HNIGsuMJlDhy?ff61182e3c2ecefa438cd0210ad0e38569b9775ddc9e06b3c362a686319250ea5c1ae2d33d8d525807641f258e33de3cb0e559c1b591b5b00fb32d5ef9&AWSAccessKeyId=AKIAJ4IAZE5EOI7PA7VQ&Expires=1352919869&Signature=OVWD9VdV7ew%2B%2Fs%2BO0YpkKZLGOCw%3D][2]

我试过的是:

Net::HTTP.start("ec-media.soundcloud.com") { |http|
  resp = http.get("/HNIGsuMJlDhy?ff61182e3c2ecefa438cd0210ad0e38569b9775ddc9e06b3c362a686319250ea5c1ae2d33d8d525807641f258e33de3cb0e559c1b591b5b00fb32d5ef9&AWSAccessKeyId=AKIAJ4IAZE5EOI7PA7VQ&Expires=1352919869&Signature=OVWD9VdV7ew%2B%2Fs%2BO0YpkKZLGOCw%3D")
  open("test.wav", "wb") { |file|
    file.write(resp.body)
  }
}
puts "Done."
sleep 50

我不了解/不知道任何互联网协议(protocol)和重定向以及其他事情...请给我一个很好的解释或帮助我使用 ruby​​ 从 soundcloud 下载文件的脚本?

谢谢

更新:

我试过这种方式,但出现错误:

Net::HTTP.start("soundcloud.com") do |http|
  resp = http.get("/dubstep-4/kill-paris-tender-love/download")

  while resp.code == '301' || resp.code == '302'
    # moved permanently or temporarily:  try again at the new location.
    resp = http.get(URI.parse(resp.header['location']))
    # ideally you should also bail if you make too many redirects.
  end

  # make sure the request was successful.
  if resp.code == '200'  
    open("test.wav", "wb"){ |file| file.write(resp.body) }
  else
    puts "Error: HTTP #{resp.code}"
  end
end

错误:

C:/Program Files (x86)/Ruby/lib/ruby/1.9.1/net/http.rb:1860:in `initialize': undefined method `empty?' for #<URI::HTTP:0x25a9ce8> (NoMethodError)
        from C:/Program Files (x86)/Ruby/lib/ruby/1.9.1/net/http.rb:2093:in `initialize'
        from C:/Program Files (x86)/Ruby/lib/ruby/1.9.1/net/http.rb:1026:in `new'
        from C:/Program Files (x86)/Ruby/lib/ruby/1.9.1/net/http.rb:1026:in `get'
        from C:/Users/Administrador/Desktop/1.rb:59:in `block in <main>'
        from C:/Program Files (x86)/Ruby/lib/ruby/1.9.1/net/http.rb:745:in `start'
        from C:/Program Files (x86)/Ruby/lib/ruby/1.9.1/net/http.rb:557:in `start'
        from C:/Users/Administrador/Desktop/1.rb:48:in `<main>'

最佳答案

有一个比 Net HTTP 更高级别的标准库,称为 Open URI。它会自动遵循重定向:

require 'open-uri'
file = open("http://soundcloud.com/stereo-f---/cohete-amigo/download")

关于Ruby - 如果 url 是重定向,如何下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13385671/

相关文章:

java - Java异常中的HTTP代码

apache - 虚假请求,证书审核员?

soundcloud - Apscheduler 运行一次然后抛出 TypeError

ruby-on-rails - Ruby - 访问查询响应的正确方法

ruby - 用散列中的值替换键

http - 我应该使用 HTTP 4xx 来指示 HTML 表单错误吗?

javascript - Soundcloud PUT API 返回 401

ruby-on-rails - 在 Rails 3 中处理 has_one 嵌套资源

sql - 新的 Ruby on Rails 开发人员需要帮助设置开发环境

javascript - 声音云和Javascript : upload music from stream