开发者

Ruby - remote file download ...timeout?

Excuse the tabs. I'm trying to download a file from remote to local and I keep getting one back that is exactly 310 bytes (regardles开发者_如何学编程s of what file I choose to download). I tried setting the timeout to 0, but this isn't working. What am I doing wrong? Thanks!

        @downloadUrl = 'https://username:password@api.net'
        Net::HTTP.start(@downloadUrl) do |http|
            response = http.get('/file.ext')
            open('/Users/me/file.ext', "wb", :read_timeout=>0) do |file|
                file.write(response.body)
            end
        end

EDIT: I don't want to use httpclient, I want to use standard net/http. I am almost there, but I keep getting initialize': getaddrinfo: nodename nor servname provided, or not known (SocketError) thrown at Net::HTTP.start(url.path). But when I remote "https", I get ECONNREFUSED. ...Getting closer?

    url = URI.parse('https://api.net/file.ext') 
    @request = Net::HTTP.start(url.path)
    @request.basic_auth 'username', 'password'
    sock = Net::HTTP.new(url.host, 443)
    sock.use_ssl = true
    sock.ssl_version='SSLv3'
    sock.start do |http|
        response = http.get(@request)
            open('/Users/me/file.ext', "wb", :read_timeout=>0) do |file|
                file.write(response.body)
            end
    end


Using httpclient is much simpler when accessing via SSL.

gem install httpclient

I haven't tried this out, but this should work for you. Here is the rdoc.

require 'httpclient'

domain    = "https://api.net/file.ext"
username  = "username"
password  = "password"

clnt = HTTPClient.new
clnt.set_auth(domain, username, password)

res = clnt.get_content(https_url)

You can refer to the "writing a binary file in ruby" question for saving your response to a file.

Updated Using net/http

You should be doing Net::HTTP.start(url.host, url.port) instead of Net:HTTP.start(url.path). See RDoc for Net::HTTP.start.

url = URI.parse("https://api.net/file.ext")
download_file = opne("/Users/me/file.ext", "wb")
request = Net::HTTP.start(url.host, url.port)

# .. set basic auth, verify peer etc

begin
  request.request_get(url.path) do |resp|
    resp.read_body { |segment| download_file.write(segment) }
  end
ensure
  download_file.close
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜