Lua
Lua
HTTP Download to Stream
See more REST Examples
Demonstrates how to stream the response body directly to a stream, which in this case is to a file stream.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
local rest = chilkat.Rest.new()
-- The URL we want to download is:
-- https://github.com/chilkatsoft/OAuth2-CSharp-Desktop/archive/master.zip
local url = chilkat.Url.new()
url:parse_url("https://github.com/chilkatsoft/OAuth2-CSharp-Desktop/archive/master.zip")
-- Connect to the web server
local bAutoReconnect = true
local success = rest:connect(url.host, url.port, url.ssl, bAutoReconnect)
if not success then
print(rest.last_error_text)
return
end
success = rest:send_req_no_body("GET", url.path)
if not success then
print(rest.last_error_text)
return
end
-- Read the response header.
local responseStatusCode = rest:read_response_header()
if responseStatusCode < 0 then
print(rest.last_error_text)
return
end
print("Response status code = " .. responseStatusCode)
-- We expect a 200 response status if the file data is coming.
-- Otherwise, we'll get a string response body with an error message(or no response body).
if responseStatusCode == 200 then
local bodyStream = chilkat.Stream.new()
-- The stream's sink will be a file.
bodyStream.sink_file = "qa_output/OAuth2-CSharp-Desktop/archive/master.zip"
-- Read the response body to the stream. Given that we've
-- set the stream's sink to a file, it will stream directly
-- to the file.
success = rest:read_resp_body_stream(bodyStream, true)
if not success then
print(rest.last_error_text)
return
end
print("Successfully downloaded the file.")
else
local errResponse = rest:read_resp_body_string()
if not rest.last_method_success then
print(rest.last_error_text)
else
print(errResponse)
end
end