Zig Cookbook

介绍

POST

解析提供的 URL 并使用 request 发出同步 HTTP POST 请求。打印获取到的 Response 状态以及从服务器接收的数据。

注意:由于 HTTP 支持尚处于早期阶段,对于任何复杂的任务,建议使用 libcurl

const std = @import("std");
const print = std.debug.print;
const http = std.http;

pub fn main(init: std.process.Init) !void {
    const gpa = init.gpa;
    const io = init.io;

    var client: http.Client = .{ .allocator = gpa, .io = io };
    defer client.deinit();

    const uri = try std.Uri.parse("https://httpbin.org/anything");

    var req = try client.request(.POST, uri, .{
        .extra_headers = &.{.{ .name = "Content-Type", .value = "application/json" }},
    });
    defer req.deinit();

    var payload: [7]u8 = "[1,2,3]".*;
    try req.sendBodyComplete(&payload);
    var buf: [1024]u8 = undefined;
    var response = try req.receiveHead(&buf);

    // Occasionally, httpbin might time out, so we disregard cases
    // where the response status is not okay.
    if (response.head.status != .ok) {
        return;
    }

    const body = try response.reader(&.{}).allocRemaining(gpa, .unlimited);
    defer gpa.free(body);
    print("Body:\n{s}\n", .{body});
}

上一示例:GET
下一示例:http.Server - std