Sample code for 30+ languages & platforms
Lua

HTTP POST and Stream Response to File

See more REST Examples

Demonstrates how to send an HTTP POST and stream the response body directly to a file.

Chilkat Lua Downloads

Lua
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()

local url = chilkat.Url.new()
-- This URL will emit a response that echos the query params (name and age)
url:parse_url("https://www.chilkatsoft.com/readPost.asp")

-- 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

rest:add_query_param("name", "John")
rest:add_query_param("age", "33")

--  Send the HTTP POST.
success = rest:send_req_form_url_encoded("POST", 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/out.txt"

    -- 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 streamed the response to a 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