0

我需要从 Amazon S3 打开一个签名的 URL,但我一直被拒绝访问。

例如,访问此 URL:

https://aidin.s3.amazonaws.com/aidin/staging/attachments/faxattach/94DD749z65ejkh353?AWSAccessKeyId=AKIAJPBOMKHDQ5WNJM3Q&Expires=1373047778&Signature=Y%2F968F9LIfkfHwsp7T8P0CqjQhQ%3D

从这段代码:

 def download path
    local_file = File.new 'attachment' + (Time.now.strftime("%Y%m%d%H%M%S")+(rand * 1000000).round.to_s) + ".pdf", 'wb+'
    # HTTPError is caught in the /process in faxattach.rb
    uri = URI.parse(path)
    http_object = Net::HTTP.new(uri.host, uri.port)
    http_object.use_ssl = true if uri.scheme == 'https'
    request = Net::HTTP::Get.new uri.request_uri
    http_object.start do |http|
      response = http.request request
      local_file.write(response.read_body)
    end
    debugger
    local_file.rewind
    local_file
  end

我得到这个local_file

<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>11A4FB2DF920A272</RequestId><HostId>6qH/f602NxfJa38oW+67Q+5GVx5XD+BJqTzNVR5IhhnvEDhiXUoTR0K90/quZTWk</HostId></Error>

有谁知道为什么?该 URL 在我的浏览器中可以正常打开,并且出于安全原因,我需要额外的查询参数AWSAccessKeyID,例如 等。Expires

4

2 回答 2

0

我会简化并使用 OpenURI:

require 'open-uri'
url = "http://aidin.s3.amazonaws.com/aidin/staging/attachments/faxattach/94DD749z65ejkh353?AWSAccessKeyId=AKIAJPBOMKHDQ5WNJM3Q&Expires=1373047778&Signature=Y%2F968F9LIfkfHwsp7T8P0CqjQhQ%3D"

File.open( 'attachment' + (Time.now.strftime("%Y%m%d%H%M%S")+(rand * 1000000).round.to_s) + ".pdf", 'wb+') do |file|
  file << open(url).read
end
于 2013-06-28T20:21:24.497 回答
0

你要request = Net::HTTP::Get.new(path)

我在上下文中的测试:

require 'net/http'
path = "https://aidin.s3.amazonaws.com/aidin/staging/attachments/faxattach/94DD749z65ejkh353?AWSAccessKeyId=AKIAJPBOMKHDQ5WNJM3Q&Expires=1373047778&Signature=Y%2F968F9LIfkfHwsp7T8P0CqjQhQ%3D"
uri = URI.parse(path)
http_object = Net::HTTP.new(uri.host, uri.port)
http_object.use_ssl = true if uri.scheme == 'https'
request = Net::HTTP::Get.new(path)
http_object.start do |http|
  response = http.request request
  puts response.read_body
end
于 2013-06-28T20:26:09.093 回答