Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.0.0+

Example: Http.HttpReq method

Demonstrates how to call the HttpReq method.

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

    var success: bool = false;

    const http = try chilkat.Http.init();
    defer http.deinit();
    success = false;

    // This example will send an HTTP POST with the body of the HTTP request containing JSON.

    // Create the following JSON: { "name": "Harry", "state": "FL" }

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("name", "Harry") catch {};
    json.updateString("state", "FL") catch {};

    // Specify the details of the request
    const req = try chilkat.HttpRequest.init();
    defer req.deinit();

    req.setHttpVerb("POST");
    req.setContentType("application/json");
    req.loadBodyFromString(try json.emit(alloc), "utf-8") catch {};

    // Send the charset attribute in the HTTP request header.
    req.setSendCharset(true);
    req.setCharset("utf-8");

    // Send the POST
    // You can send the POST to the URL below.
    // The response will contain the raw body of the request that was sent.
    // (i.e. everything except the HTTP request header).

    const resp = try chilkat.HttpResponse.init();
    defer resp.deinit();
    http.httpReq("https://www.chilkatsoft.com/echo_request_body.asp", req, resp) catch {
        std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
        return;
    };

    // Examine the HTTP request header we sent:
    std.debug.print("{s}\n", .{try http.getLastHeader(alloc)});

    // The response body contains the raw content of the HTTP request body we sent.
    std.debug.print("{s}\n", .{try resp.getBodyStr(alloc)});

    // Sample output:

    // POST /echo_request_body.asp HTTP/1.1
    // Host: www.chilkatsoft.com
    // Content-Type: application/json; charset=utf-8
    // Content-Length: 29
    //
    //
    // {"name":"Harry","state":"FL"}
}