Question

I am trying to make POST request with Net::HTTP to specific website, and start downloading file after response is returned. I tested this first with wget, and it worked fine.I also tried with httpi and unirest gems and it went fine . However, because Net::HTTP is low-level API and I need more control(for example, tracking downloading progress), I'll stick with it. The problem is, downloading just won't start.So here's the code:

require 'net/http'
require 'tempfile'
uri = URI.parse("http://mywebsite.com")
req = Net::HTTP::Post.new(uri.path)
req.set_form_data({'filed' => 'data'})


response = Net::HTTP.start(uri.hostname, uri.port) {|http|
  http.request(req) do |response|
   temp_file = Tempfile.new("new_file")
   response.read_body do |chunk|
        temp_file << chunk
   end

 end
}

I figured that the problem must be in response, what I get is not Net::HTTPOK but HTTPSeeOther and here's more info about it

      #<Net::HTTPSeeOther:0x91f2670>
            {"server"=>["nginx"], "date"=>["Sat, 21 Dec 2013 22:32:14 GMT"], 
        "content-type"=>["text/html"], "transfer-encoding"=>["chunked"], 
            "connection"=>["keep-alive"], "pragma"=>["no-cache"], 
            "cache-control"=>["no-cache, must-revalidate"], 
    "expires"=>["Sat, 26 Jul 1997 05:00:00 GMT"], 
"location"=>["http://mywebsite.com/path/to/file.rar"]}

The other 2 gems I mentioned knew how to start download automatically and I don't know what to do with HTTPSeeOther .

Was it helpful?

Solution

It appears that you're getting a redirect response from the server, which wget, curl, and high-level libraries will follow automatically. With Net::HTTP, you'll need to start a new GET request to that location.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top