LEVIATHAN v962456e · 962456eee1

Standard Library

class HttpClient

A simple HTTP client that sends one request per connection and delivers the response to a callback.

since 0.1.0-alpha.1linux

Overview

Name the server by host, port and path; there is no URL parsing and redirects are not followed. Each call opens a new connection, sends Connection: close, reads the response until the server closes the connection, and calls your function with the parsed HttpResponse. A response body that is chunked is decoded for you. The Tls forms of each method use HTTPS and always check the server's certificate and host name.

A connection that cannot be opened is reported by throwing a RuntimeException from the call itself. The program keeps running until the response has arrived. Use fetch and fetchTls to receive the response with await instead of a callback.

Description

HttpClient has no state; create one and call it. Every method takes the host, the port and the path separately, because the client does not parse URLs.

  • fetch(host, port, path) returns a Promise<HttpResponse> for a GET. This is the convenient form in straight-line code: HttpResponse r = await client.fetch(...);.
  • get(host, port, path, callback) and post(host, port, path, body, callback) are the callback forms of the common requests.
  • request(method, host, port, path, headers, body, callback) is the general form: any method, your own HeaderMap of extra headers, and a body. The client adds Host, Connection: close, and a Content-Length when the body is not empty, and drops any of those names you supply so the request on the wire stays consistent.
  • requestTls, getTls, postTls and fetchTls do the same over HTTPS. The certificate chain and host name are always fully verified. See lang.tls.

The response arrives as an HttpResponse, whose status, headers and body you read directly. A chunked response is decoded for you. The client reads until the server closes the connection, then parses what it received.

A connection that cannot be opened throws a RuntimeException (TCP connect failed (host '...', port ...)) from the call that tried to open it; the request is not retried.

Rules

  • One connection is opened per request, and it is closed after the response. There is no connection pooling.
  • Pass host, port and path separately. Redirects are not followed, and there is no request timeout. To stop waiting after a while, wrap fetch in awaitTimeout; that stops the waiting, not the request (see lang.cancellation).
  • Bodies are text.
  • The callback runs on the event loop once the whole response has arrived.
  • HTTPS verification cannot be switched off through HttpClient.

Examples

Fetching a page with await, then posting JSON with the callback form:

HttpClient client = HttpClient();
HttpResponse r = await client.fetch("example.com", 80, "/");
console.writeln("status ${r.status}");
console.writeln(r.headers.first("Content-Type") ?? "no content type");
console.writeln("body is ${r.body.length()} bytes");

HeaderMap extra = HeaderMap();
extra.set("Accept", "application/json");
client.request("POST", "example.com", 80, "/items", extra, "{}", (resp) => {
    console.writeln("created: ${resp.status == 201}");
});
not run — needs the network

Notes

Not implemented: redirects, URL-string parsing, request timeouts, pipelining, and sending a body in chunks from the client.

Examples

Fetching a page

HttpClient client = HttpClient();
client.get("example.com", 80, "/", (resp) => {
    console.writeln("${resp.status} ${resp.reason()}");
    console.writeln(resp.body);
});
not run — needs the network

Several calls

HttpClient client = HttpClient();
HeaderMap headers = HeaderMap();
headers.add("Content-Type", "application/json");
client.request("PUT", "example.com", 80, "/item/1", headers, "{}", (r) => console.writeln(r.status));
client.postTls("example.com", 443, "/submit", "a=1", (r) => console.writeln(r.status));

Methods

fetch

fetch(string host, int port, string path) -> Promise<HttpResponse>

Sends a GET request and returns a promise of the response.

This is get for code that uses await: HttpResponse r = await client.fetch(host, port, path);.

Parameters

host
The server's host name or address.
port
The server's port number.
path
The request path, including any query string.

Returns

A promise that resolves with the response.

Throws

RuntimeException
when no connection to the host and port can be opened.

See also: get

fetchTls

fetchTls(string host, int port, string path) -> Promise<HttpResponse>

Sends a GET request over HTTPS and returns a promise of the response.

This is getTls for code that uses await.

Parameters

host
The server's host name, which is also the name the certificate must match.
port
The server's port number, usually 443.
path
The request path, including any query string.

Returns

A promise that resolves with the response.

Throws

RuntimeException
when no connection can be opened or the server's certificate is rejected.

See also: fetch

get

get(string host, int port, string path, (HttpResponse) => void onResp) -> void

Sends a GET request and calls a function with the response.

Parameters

host
The server's host name or address.
port
The server's port number.
path
The request path, including any query string.
onResp
The function called with the response once it has arrived.

Throws

RuntimeException
when no connection to the host and port can be opened.

See also: request, fetch

getTls

getTls(string host, int port, string path, (HttpResponse) => void onResp) -> void

Sends a GET request over HTTPS and calls a function with the response.

Parameters

host
The server's host name, which is also the name the certificate must match.
port
The server's port number, usually 443.
path
The request path, including any query string.
onResp
The function called with the response once it has arrived.

Throws

RuntimeException
when no connection can be opened or the server's certificate is rejected.

See also: requestTls

post

post(string host, int port, string path, string body, (HttpResponse) => void onResp) -> void

Sends a POST request with a body and calls a function with the response.

Parameters

host
The server's host name or address.
port
The server's port number.
path
The request path.
body
The request body.
onResp
The function called with the response once it has arrived.

Throws

RuntimeException
when no connection to the host and port can be opened.

See also: request

postTls

postTls(string host, int port, string path, string body, (HttpResponse) => void onResp) -> void

Sends a POST request over HTTPS with a body and calls a function with the response.

Parameters

host
The server's host name, which is also the name the certificate must match.
port
The server's port number, usually 443.
path
The request path.
body
The request body.
onResp
The function called with the response once it has arrived.

Throws

RuntimeException
when no connection can be opened or the server's certificate is rejected.

See also: requestTls

request

request(string method, string host, int port, string path, HeaderMap headers, string body, (HttpResponse) => void onResp) -> void

Sends a request with any method, headers and body, and calls a function with the response.

The Host header is added from host, and Connection: close is added. A Content-Length header is added when body is not empty. Headers you pass named Host, Connection or Content-Length are ignored, so the computed values are the only ones.

Parameters

method
The request method, such as GET or PUT.
host
The server's host name or address.
port
The server's port number.
path
The request path, including any query string.
headers
Extra headers to send.
body
The request body; empty for none.
onResp
The function called with the response once it has arrived.

Throws

RuntimeException
when no connection to the host and port can be opened.

See also: get

requestTls

requestTls(string method, string host, int port, string path, HeaderMap headers, string body, (HttpResponse) => void onResp) -> void

Sends a request over HTTPS with any method, headers and body, and calls a function with the response.

It works like request, but the connection is secured. The server's certificate chain and host name are always checked, and a server that fails the check is rejected with a RuntimeException before any request is sent.

Parameters

method
The request method, such as GET or POST.
host
The server's host name, which is also the name the certificate must match.
port
The server's port number, usually 443.
path
The request path, including any query string.
headers
Extra headers to send.
body
The request body; empty for none.
onResp
The function called with the response once it has arrived.

Throws

RuntimeException
when no connection can be opened or the server's certificate is rejected.

See also: request

See also

  • HttpServer — A web server that listens on a port and answers each request with a handler function.
  • HttpResponse — An HTTP response: a status code, headers and a body.
  • HeaderMap — An ordered collection of HTTP headers whose names are matched without regard to letter case.
  • TcpStream — A connected network socket that reads and writes text.