Sample code for 30+ languages & platforms
Zig

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

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const rest = try chilkat.Rest.init();
    defer rest.deinit();

    const url = try chilkat.Url.init();
    defer url.deinit();
    // This URL will emit a response that echos the query params (name and age)
    url.parseUrl("https://www.chilkatsoft.com/readPost.asp") catch {};

    // Connect to the web server
    const b_auto_reconnect = true;
    rest.connect(try url.getHost(alloc), url.getPort(), url.getSsl(), b_auto_reconnect) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    rest.addQueryParam("name", "John") catch {};
    rest.addQueryParam("age", "33") catch {};

    //  Send the HTTP POST.
    rest.sendReqFormUrlEncoded("POST", try url.getPath(alloc)) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    // Read the response header.
    const response_status_code = rest.readResponseHeader();
    if (response_status_code < 0) {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    }

    std.debug.print("Response status code = {d}\n", .{response_status_code});

    // 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 (response_status_code == 200) {
        const body_stream = try chilkat.Stream.init();
        defer body_stream.deinit();

        // The stream's sink will be a file.
        body_stream.setSinkFile("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.
        rest.readRespBodyStream(body_stream, true) catch {
            std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
            return;
        };

        std.debug.print("Successfully streamed the response to a file.\n", .{});
    } else {
        const err_response = rest.readRespBodyString(alloc) catch "";
        if (!rest.getLastMethodSuccess()) {
            std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        } else {
            std.debug.print("{s}\n", .{err_response});
        }
    }
}