Skip to content
Jennifer Programming Language

http - an HTTP/1.1 client

Import with import "http.j" as http;. An HTTP/1.1 client over the net system library: build a request (method, URL, headers, body), send it, and read the response back into a Response (status, headers, body). http:// connects in the clear; https:// connects with TLS (net.connectTLS); any other scheme, or none, is refused before anything is sent. Because it uses net, this module needs the default jennifer binary.

On jennifer-tiny: "needs the default jennifer binary" refers to the stock tiny build, which ships without a network driver - not a TinyGo limitation. A jennifer-tiny rebuilt with a network stack runs this module too; see the note on net and TinyGo.

jennifer
use io;
import "http.j" as http;

def r as http.Response init http.get("http://example.com/", {});
io.printf("status %d\n%s\n", $r.status, $r.body);

def sent as http.Response init http.post("https://api.example.com/items",
    "application/json", '{"name":"ada"}', {"Authorization": "Bearer xyz"});

Runnable: examples/modules/http_demo.j.

Surface

headers is a map of string to string (pass {} for none); a body is a string ("" for none).

Call / typeNotes
http.Responsestatus (int), statusText, headers (lowercased keys), body (string, UTF-8).
http.BytesResponseSame, but body is raw bytes - the byte-safe response for binary downloads.
http.request(method, url, headers, body)One request with the defaults (send with zero Options); returns a Response.
http.sendBytes(method, url, headers, body, options)send with a raw bytes body (written byte-for-byte: a multipart/form-data upload, a protobuf) and a BytesResponse; same redirects, retries and cookies. Set your own Content-Type.
http.getBytes(url, headers)GET returning a raw-bytes body (the download shortcut).
http.get(url, headers)GET.
http.post(url, contentType, body, headers)POST; sets Content-Type.
http.put(url, contentType, body, headers)PUT; sets Content-Type.
http.patch(url, contentType, body, headers)PATCH (partial update); sets Content-Type.
http.delete(url, headers)DELETE.
http.head(url, headers)HEAD (status + headers, no body).
http.options(url, headers)OPTIONS (capability probe; read the Allow header).
http.header(resp, name)Read a response header case-insensitively, or "" if absent.
http.basic(user, pass)Build a Basic <base64> Authorization value (mirrors rest.basic).
http.isCleartextRemote(url)true for an http:// URL to a host other than loopback (127.0.0.0/8, [::1], localhost): credentials sent there cross the network in the clear. false for https:// and loopback http://; kind "http" for a URL a request would refuse.
http.sendDigest(method, url, headers, body, options, user, password)send with HTTP Digest auth: answers a 401 Digest challenge once (twice for a stale nonce). See Digest auth.
http.digestAuthorization(challenge, method, url, user, password, body)The Authorization value answering a WWW-Authenticate Digest challenge, for any other request call.
http.OptionsRequest policy, see Options. Zero value = defaults, verified TLS, no redirects, no retries, only non-credential headers kept on a cross-origin redirect, and an https:// to http:// redirect refused.
http.defaultOptions()The zero Options, for inline use.
http.send(method, url, headers, body, options)One request with policy: follow up to maxRedirects 3xx, retry a 429 / 5xx up to maxRetries with backoff, carry cookies across the redirect chain. A redirect to a different origin keeps only Accept, Accept-Encoding, Accept-Language, Cache-Control, Content-Language, Content-Type, If-*, Pragma, Range and User-Agent and drops the cookie jar, so Authorization, Cookie and any custom key header (X-API-Key, PRIVATE-TOKEN, ...) stay behind, unless allowCrossOriginRedirect is set; a redirect from https:// to http:// throws unless allowInsecureRedirect is set. Returns a Response.
http.SessionA persistent (keep-alive) connection to one origin, with a cookie jar.
http.Exchangeresponse (Response) + session (Session) to thread onward.
http.connect(url, options)Open a persistent Session to the origin of url.
http.exchange(session, method, path, headers, body)One request over the reused socket; returns an Exchange.
http.close(session)Close a Session's connection.

The response body is bounded by default: http reads at most 64 MiB (MAX_BODY_BYTES) and raises a catchable error beyond it. The per-read timeout only bounds a stalled server; the size cap keeps a hostile server (e.g. behind an untrusted URL a feed reader follows) from streaming an unbounded body into memory. To change it, set Options.maxBytes for send / sendBytes: 0 keeps the 64 MiB default, math.MAX_INT lifts the cap for a trusted large download, a positive value sets an exact ceiling, a negative value throws. The s3 module lifts it for object downloads; the verb shortcuts (get / post / ...) and request keep the default.

The cap counts body bytes only: a body of exactly maxBytes bytes is read, one byte more is the error http: response body exceeds N bytes. For a chunked body that is the decoded data, checked as each chunk size arrives, so an over-size body fails before its data is read. The status line and headers have a cap of their own, 1 MiB (MAX_HEADER_BYTES), whatever maxBytes says - an unlimited body does not mean unlimited headers - and a larger head is the error http: response headers exceed 1048576 bytes. Under a body cap, a chunked body's framing (its size lines, CRLFs and trailers) may add at most the larger of the cap and 1 MiB on top (http: chunked framing exceeds N bytes beyond it), so a server cannot stream without end behind a small cap.

The three are errors of kind "limit", not "http": a cap was reached, the exchange itself did not fail. Catch them by kind ($e.kind == "limit") rather than by matching the message.

The shortcuts are thin wrappers over request, which sends whatever method string you pass, so a method without a shortcut works too: http.request("TRACE", url, {}, ""). CONNECT is not supported: it is the HTTP tunneling primitive (after a 200 the socket becomes a raw bidirectional tunnel), which needs a connection hand-off this request/response-then-close client does not do.

Request policy: redirects, retries, cookies

http.send is a one-shot request plus a policy, configured by an http.Options. The zero Options (http.defaultOptions()) behaves exactly like request; set a field to opt in:

jennifer
import "http.j" as http;
def o as http.Options;
$o.maxRedirects = 5;   # follow up to 5 3xx redirects
$o.maxRetries = 3;     # retry a 429 / 5xx up to 3 times
$o.backoffMs = 250;    # first backoff (doubles per attempt), honours Retry-After
def r as http.Response init http.send("GET", "https://example.com/", {}, "", $o);
  • Redirects. A 301 / 302 / 303 / 307 / 308 with a Location is followed up to maxRedirects hops (0 returns the 3xx as-is). A 303 (and a 301/302 on a POST) becomes a bodyless GET; 307 / 308 preserve the method and body. Cookies set along the chain are replayed on later hops. A hop from https:// to plain http:// would send the next request (path, and the body on a 307 / 308) unencrypted, so it throws Error{kind: "http"} unless allowInsecureRedirect is set. A network-path Location (//host/path) keeps the current scheme; a relative one (../next, ?page=2) resolves as RFC 3986 says (uri.resolve).
  • Retries. A 429 or 5xx is retried up to maxRetries with exponential backoff (backoffMs * 2^attempt), raised to the server's Retry-After when it asks for longer, and clamped to 30s. Retry-After is delay-seconds (leading zeros allowed: 0000001 is 1 s) or an HTTP-date (the IMF-fixdate Sun, 06 Nov 1994 08:49:37 GMT, and the obsolete RFC 850 and asctime forms RFC 9110 has recipients accept); a date in the past asks for no wait, a malformed value counts as absent, and a date past the year 2262 (the end of time's range) is past the cap anyway. Any method is retried, so set maxRetries on a POST only when the server's answer to a repeat is safe (an idempotency key, or a 429 / 503 that did nothing).

Options

FieldZero valueNotes
timeoutMs30000Idle timeout for each read and each 16 KiB written, and the connect's deadline. math.MAX_INT = no idle timeout (the connect still gives up after 30 s).
maxBytes64 MiBResponse-body cap, see Response body and framing. math.MAX_INT = unlimited.
maxRedirects0 (none)3xx hops to follow.
maxRetries0 (none)Retries of a 429 / 5xx.
backoffMs250First retry backoff, doubled per attempt, capped at 30 s.
tlsOptionsverify against the system rootsA net.TLSOptions, see TLS.
tls-Deprecated (http.TlsOptions), removed in 0.29.0; set tlsOptions. Setting both throws.
allowCrossOriginRedirectfalseKeep every header and the cookies across a cross-origin redirect.
allowInsecureRedirectfalseFollow an https:// to http:// redirect.

A negative number in any field, or both tls and tlsOptions set, throws Error{kind: "http"} before anything is sent. connect / exchange take the same Options.

For Basic auth, http.basic(user, pass) builds the header value:

jennifer
import "http.j" as http;
def url as string init "https://example.com/private";
def r as http.Response init http.get($url, {"Authorization": http.basic("ada", "s3cret")});

Basic credentials are only encoded, not encrypted: send them over https://. Modules that attach credentials for you (graphql, jsonrpc, soap, mcp, webdav, ...) refuse a plain http:// URL to anything but a loopback host unless told otherwise (allowInsecureHttp); http.isCleartextRemote(url) is the test they use.

Digest auth

http.sendDigest sends the request without credentials and answers a 401 whose WWW-Authenticate carries a Digest challenge (RFC 7616; the RFC 2617 and RFC 2069 forms too), the way cameras, routers and older appliances ask:

jennifer
use os;
import "http.j" as http;
def password as string init os.getEnv("CAMERA_PASSWORD");
def r as http.Response init http.sendDigest(
    "GET", "http://192.168.1.20/ISAPI/Streaming/channels/1/picture", {}, "",
    http.defaultOptions(), "admin", $password);
  • Choice: the strongest challenge offered wins: SHA-256, SHA-256-sess, MD5, MD5-sess (SHA-512-256 is not supported). qop=auth when offered, else auth-int, which hashes the body; without qop, the RFC 2069 form. userhash and opaque are honoured. Each answer uses a fresh 128-bit client nonce and nc=00000001; nothing is cached between calls, so every call costs the challenge round trip.
  • Retries: a second 401 is returned as is (a wrong password), except when it reports the nonce stale, which is answered once more. A 401 offering only another scheme (Basic, Bearer) is returned unanswered.
  • Origin: the challenge round follows no redirect, so the answer goes to the URL given and no other; a 3xx there is returned. The authenticated request then uses options in full, and send drops Authorization on a cross-origin hop. An Authorization among headers is replaced.
  • Safety: a control character in the challenge's realm, nonce or opaque, the user name or the request target is refused (Error{kind: "http"}), so a server cannot inject header lines into the answer.
  • Other calls: for a byte download or a Session, read the challenge from the 401 and send http.digestAuthorization(challenge, method, url, user, password, body) as Authorization yourself.

Digest keeps the password off the wire, but MD5 is weak and the exchange is still readable over http://; prefer https:// where the device has it.

Persistent connections (keep-alive)

http.connect opens a Session to one origin (scheme + host + port) and reuses the socket across exchange calls, so a request loop pays a single handshake instead of one per request. The Session is value-semantic, but its underlying net.Conn is a shared handle - thread the returned session forward:

jennifer
import "http.j" as http;
def s as http.Session init http.connect("https://api.example.com", http.defaultOptions());
def x1 as http.Exchange init http.exchange($s, "GET", "/items?page=1", {}, "");
$s = $x1.session;                 # carry the reused socket + any cookies
def x2 as http.Exchange init http.exchange($s, "GET", "/items?page=2", {}, "");
$s = $x2.session;
http.close($s);

exchange maintains a small cookie jar on the session (name -> value; it preserves multiple Set-Cookie lines and replays them as one Cookie header) and reconnects transparently when a response said it would close the connection. A server that drops an idle connection unannounced (a keep-alive timeout racing the next request) shows as the reused socket closing or resetting before a single byte of the answer: exchange then dials a new connection and sends the request once more, but only when repeating it is safe - an idempotent method (GET, HEAD, OPTIONS, TRACE, PUT, DELETE, RFC 9110 9.2.2) or a request carrying an Idempotency-Key header. Any other request (a POST, a PATCH) may already have been acted on, so the net.NetError (reason "closed" or "reset", replied false) reaches the caller, as does any failure on a socket dialed by that very call. When an exchange fails partway (a timeout, a bad response), its socket is closed so the late answer can never be read as the next one's; the next exchange on the session dials a new connection. It does not follow redirects (a redirect can cross origins and break the socket) - use http.send for that; exchange returns the 3xx.

The jar has no domain / path scoping and no expiry (see Out of scope).

URLs and headers

A URL is parsed into scheme / host / port / path. The scheme must be http:// or https:// (case-insensitive): a URL with no scheme (host/path) or another one (a typo like htps://, or ftp://) throws Error{kind: "http"} before any connection opens, rather than going out as plain HTTP - for a webhook or token URL the path is the secret. The message leaves the URL out for the same reason. Plain http:// stays allowed; requiring https:// is the caller's policy. http:// defaults to port 80, https:// to 443, an explicit :port overrides, and the path (with any query string) defaults to /. A URL with no host, a port outside 1 to 65535 or an unclosed [ throws Error{kind: "http"}, and so does whitespace or a control character in the path (percent-encode it). Credentials in the URL (user:pass@) are dropped, never sent; use http.basic. The Host header is set automatically (with the port when non-default), along with Connection: close and a default User-Agent (overridable by supplying your own).

The client owns the headers that frame a request: a caller's Host, Connection, Content-Length or Transfer-Encoding is left out. The one exception is a Host that names the URL's own host and port, such as 192.168.1.5:80 for http://192.168.1.5/: it is sent as written, for devices that want the default port spelled out. An empty POST / PUT / PATCH is sent with Content-Length: 0, which some servers require. A method or header name that is not an HTTP token, or a CR / LF / NUL in a header value, throws Error{kind: "http"} before anything is sent.

Response header names are lowercased (HTTP header names are case-insensitive), so $r.headers["content-type"] works regardless of how the server cased it; http.header($r, "Content-Type") case-folds the name.

Response body and framing

The client frames the response from its own headers (RFC 9112 6.3), so a request returns as soon as the body is complete - it does not wait for the connection to close, even though it sends Connection: close. A server that ignores that token and holds the socket open (some appliances and proxies) works the same as one that closes. Framings:

  • Content-Length - the body is taken as exactly that many bytes.
  • Transfer-Encoding: chunked - the chunks are decoded and concatenated. The reader follows the chunk framing as it arrives, so it stops right after the last chunk and any trailers. A malformed chunk-size line or a chunk not ended by CRLF is an Error{kind: "http"}, never a silently short body, and so is a Content-Length that is not a number or two that disagree.
  • Neither - the body runs to connection close (the last-resort framing).

Some responses have no body whatever their headers say (RFC 9110): the answer to a HEAD request, and every 1xx / 204 / 304. Their Content-Length (or Transfer-Encoding) describes the body a GET would return, so the client reads only the head - it never waits for those bytes, and the maxBytes cap is not checked against them. http.head(url, {}) therefore asks "does it exist, how big is it" without downloading anything (read the size with http.header($r, "content-length")). An interim 1xx such as 100 Continue or 103 Early Hints is skipped and the final response returned (at most 32 of them); 101 Switching Protocols is final.

request and the verb shortcuts return the body as text (UTF-8): a JSON / HTML / XML body round-trips exactly, but a binary body (an image, a gzip stream) is not valid UTF-8 and raises an error. For binary content use the byte verbs below, which return the body as raw bytes - the framing above is byte-exact, so only the text decode differs.

Binary downloads

http.getBytes(url, headers) (and the general sendBytes) return an http.BytesResponse whose body is raw bytes - the byte-safe path for a .tar.gz, an image, or any non-text payload the string Response cannot hold:

jennifer
use fs;
use compress;
use archive;
import "http.j" as http;
def r as http.BytesResponse init http.getBytes("https://example.com/app.tar.gz", {});
fs.writeBytes("app.tar.gz", $r.body);                  # exact bytes, no corruption
def entries as list of archive.Entry init archive.unpack("tar", compress.unpack("gzip", $r.body));

headers keys are lowercased, so read metadata directly ($r.headers["content-type"]). A large download that would exceed the default 64 MiB cap sets maxBytes: math.MAX_INT (unbounded); the same Options carry tlsOptions for a self-signed host:

jennifer
use math;
import "http.j" as http;
def o as http.Options;
$o.maxBytes = math.MAX_INT;
def none as bytes;
def r as http.BytesResponse init http.sendBytes("GET", "https://example.com/big.iso", {}, $none, $o);

Timeouts

The initial connect (and, for https, the TLS handshake) is bounded by a connection-establishment timeout, so a slow or unreachable server fails the dial instead of blocking it forever. Every request then carries an idle timeout (default 30 s): the deadline is re-armed before each read, and before each 16 KiB of the request written, so a server that accepts the connection and then stalls fails with a catchable read timed out error, and hung connections cannot pile up. Set a different value (in milliseconds) in Options.timeoutMs; math.MAX_INT disables the idle timeout for that request (e.g. a long streaming download):

jennifer
use io;
import "http.j" as http;
def url as string init "https://example.com/slow";
def o as http.Options;
$o.timeoutMs = 5000;   # 5 s, default body cap
try {
    def r as http.Response init http.send("GET", $url, {}, "", $o);
} catch (e) {
    io.printf("request timed out or failed\n");
}

The timeout bounds each read and each 16 KiB written, not the whole transfer, so a large but steady download or upload is fine while a stalled one is cut off.

TLS (self-signed / private CA)

An https:// request full-verifies the server certificate against the URL host by default. To reach a server with a self-signed or private-CA certificate (a LAN appliance, an internal service), set Options.tlsOptions, a net.TLSOptions, for send / sendBytes / connect. The zero value verifies, so request and the verb shortcuts are unchanged; http:// ignores it.

jennifer
use fs;
import "http.j" as http;
def o as http.Options;
$o.tlsOptions.caCert = fs.readBytes("appliance-ca.pem");   # trust this cert (preferred)
def r as http.Response init http.send("GET", "https://192.168.1.10/", {}, "", $o);
  • caCert (bytes, PEM) trusts the certificates it holds instead of the system roots. Preferred: the server stays authenticated.
  • skipVerify (true) accepts any certificate. It disables authentication and exposes the connection to a man-in-the-middle - use only for a trusted LAN endpoint you cannot give a proper CA.

Options.tls (an http.TlsOptions, the same two fields) is deprecated and removed in 0.29.0; setting it and tlsOptions both throws Error{kind: "http"}.

Errors

A non-2xx status is not an error - a 404 or 500 comes back as a normal Response with that status, for the caller to branch on. Everything else raises a positioned error; dispatch on its kind:

KindWhenRetry?
"net"the network failed: a net.NetError (see net) with op, reason, and the exchange facts sent (the whole request was written) and replied (some of the answer arrived). A server that closes without sending a byte of its answer is reason "closed", sent true, replied falsewhen sent is false (a refused connection, a failed lookup or handshake: the request never reached the server); otherwise only if the request is idempotent
"timeout"a connect, read or write deadline passedas "net", but the message is all it says
"closed"the server closed the connection after part of its answer (a cut head, a short Content-Length body, a chunked body without its last chunk)only if idempotent: the server got the request
"limit"the body, the head or the chunked framing passed its capno
"http"a malformed answer (see below), a bad URL or header, an Options field out of range, a refused https -> http redirectno

A malformed answer is never repaired: a status line other than HTTP/1.x with a three-digit code, a header line without a colon, with a space before the colon or a name that is not a token, a folded continuation line (obs-fold), a control character in a value, head bytes that are not UTF-8, a Transfer-Encoding other than a lone chunked (the client asks for no other transfer coding) or one next to a Content-Length, and a malformed or conflicting Content-Length all throw kind "http". So does a body that is not valid UTF-8 in a text Response; use the Bytes verbs for binary bodies.

Reading the fields as a net.NetError needs use net; in the file.

jennifer
use net;
import "http.j" as http;
def url as string init "https://api.example.com/items";
def body as string init '{"name":"ada"}';
try {
    def r as http.Response init http.post($url, "application/json", $body, {});
} catch (e) {
    if ($e.kind == "net") {
        def ne as net.NetError init $e;
        if (not $ne.sent) {
            # the request never reached the server: safe to send again
        }
    }
    throw $e;
}

Out of scope

  • Redirects. The one-shot verbs return a 3xx as-is; http.send follows them (with a hop limit). No auto-follow on the persistent exchange path (it can cross origins).
  • Connection reuse is per-origin and single-request. connect / exchange keep one socket alive to one origin; there is no cross-origin connection pool and no request pipelining.
  • Cookie jar is session-scoped. Session keeps a name -> value jar with no domain / path scoping or expiry (a full RFC 6265 store is not implemented); the one-shot verbs keep no cookies. No automatic decompression, no multipart builder - set the headers and body you need directly.
  • Binary bodies use sendBytes / getBytes; the text path decodes UTF-8.

Deprecated

Removed in 0.29.0; jennifer lint reports each call (L301). The positional timeoutMs 0 of these functions is no idle timeout, math.MAX_INT in Options; a negative timeoutMs or maxBytes throws, as in Options.

DeprecatedUse
requestWith(m, u, h, body, timeoutMs, maxBytes)send(m, u, h, body, Options{timeoutMs, maxBytes})
requestTls(m, u, h, body, tls)send(m, u, h, body, Options{tlsOptions})
requestWithTls(m, u, h, body, timeoutMs, maxBytes, tls)send(m, u, h, body, Options{timeoutMs, maxBytes, tlsOptions})
requestRawBody(m, u, h, bytes, timeoutMs, maxBytes)sendBytes(m, u, h, bytes, Options{timeoutMs, maxBytes}) (a BytesResponse)
requestRawBodyTls(m, u, h, bytes, timeoutMs, maxBytes, tls)sendBytes(m, u, h, bytes, Options{timeoutMs, maxBytes, tlsOptions})
requestBytes(m, u, h, body)sendBytes(m, u, h, bytes, defaultOptions())
requestWithBytes(m, u, h, body, timeoutMs, maxBytes, tls)sendBytes(m, u, h, bytes, Options{timeoutMs, maxBytes, tlsOptions})
http.TlsOptions, Options.tlsnet.TLSOptions, Options.tlsOptions

See also

  • net.md - the transport (and its TLS) http builds on.
  • json.md - encode / decode JSON request and response bodies.
  • modules/index.md - the module catalog and import rules.

API reference

Every exported function, struct and constant of http, with its signature, generated from the module's doc comments: the http API reference.