HTTP client
import "std/net" (not included in import "std") · namespace std.net
HttpClient sends HTTP/1.1 requests to http:// and https:// URLs. It keeps connections open and reuses them for the next request to the same server, so a client that is kept around is much faster than a new one per request; one client can be shared by many threads.
grav
import "std"
import "std/net"
fn main() {
let app = new HttpServer()
app.get("/whoami", fn(req: HttpRequest) => HttpResponse.text("token " + req.bearerToken()))
app.post("/login", fn(req: HttpRequest) => HttpResponse.text("ok").setCookie("sid", "42"))
app.get("/session", fn(req: HttpRequest) => HttpResponse.text("sid " + req.cookie("sid")))
app.get("/old", fn(req: HttpRequest) => HttpResponse.redirect("/session", 301))
app.start(0)
let base = app.baseUrl()
let api = new HttpClient().setBearerToken("abc").useCookies(true)
print(api.get(base + "/whoami").body())
api.post(base + "/login", "", "")
print(api.get(base + "/old").body()) // redirected, with the cookie
for (i in 0..10) { api.get(base + "/whoami") }
print("idle connections: ${api.idleConnections()}")
api.close()
app.stop()
}token abc
sid 42
idle connections: 1- Methods:
get,head,options,delete,post,put,patch, the JSON formspostJson,putJson,patchJson,getJsonandgetText(both throw on a non-2xx status),postForm(fields)/postForm(formData)(multipart when it has files),download(url, path), and the generalsend(method, url, body, contentType, headers). - Responses of any status are returned (check
ok()or callensureOk()); network failures throwNetError, slow serversTimeoutErroraftertimeoutMs.elapsedMssays how long the request took. - Settings: default
headers,setBasicAuth(user, pw)or credentials in the URL (http://user:pw@host/),setBearerToken(token),useCookies(true)for a browser-like session,maxRedirects(0 to see redirects yourself),keepAlive,maxIdlePerHost,maxResponseBytes. - HTTPS verifies the server's certificate against the system's trusted authorities and its host name.
withTls(ctx)changes what is trusted, for exampleTlsContext.client().trustPem(pem)for a private CA or a self-signed test server. - Redirects: 301/302/303 turn a POST into a GET, 307/308 repeat the request with its body. Credentials are dropped when a redirect leads to another server.
- Compression: requests say
Accept-Encoding: gzip, deflate, and compressed responses are decoded before you see them (withinmaxResponseBytes);wasCompressedtells which were. Setdecompress = falseto get the raw bytes. - HTTPS reconnects resume the earlier TLS session with the server, which skips the certificate check and signature of a full handshake.
HttpClient.fetch(url)is a one-off GET;close()closes pooled connections.
API
class HttpClient
An HTTP/1.1 client with a connection pool.
Constructors
new HttpClient()
Static members
static fn fetch(url: string) -> HttpResponse— One-off GET with default settings.
Fields
timeoutMs: int— Give up on connecting or waiting for data after this long (0 = never).headers: Headers— Sent with every request.maxRedirects: int— Follow 301/302/303/307/308 redirects up to this many times (0 = never).keepAlive: bool— Reuse connections between requests (on by default).maxIdlePerHost: int— Idle connections kept per server.maxResponseBytes: int— Responses larger than this many bytes throw NetError.tls: TlsContext— The TLS settings for https:// (null: verify against the system's CAs).decompress: bool— Ask for compressed responses (gzip, deflate) and decompress them (on by default).
Methods
fn setBasicAuth(user: string, password: string) -> HttpClient— Sends "Authorization: Basic ..." with every request; returns this client.fn setBearerToken(token: string) -> HttpClient— Sends "Authorization: Bearer <token>" with every request; returns this client.fn useCookies(on: bool) -> HttpClient— Remembers cookies servers set and sends them back (per host), like a browser session; returns this client.fn cookiesFor(host: string) -> HashMap<string, string>— The cookies remembered forhost(name -> value).fn withTls(ctx: TlsContext) -> HttpClient— Trusts servers verified byctxfor https:// (e.g. one that trusts a private CA); returns this client.fn close()— Closes the pooled idle connections.fn idleConnections() -> int— Idle connections held for reuse, across all servers.fn get(url: string) -> HttpResponse— Sends a GET request.fn getJson(url: string) -> JsonValue— Sends a GET request and parses the body as JSON; NetError for a non-2xx status.fn getText(url: string) -> string— Sends a GET request and returns the body; NetError for a non-2xx status.fn head(url: string) -> HttpResponse— Sends a HEAD request (headers only).fn options(url: string) -> HttpResponse— Sends an OPTIONS request (what a server allows; CORS preflights).fn delete(url: string) -> HttpResponse— Sends a DELETE request.fn post(url: string, body: string, contentType: string) -> HttpResponse— Sends a POST request with a body of the given Content-Type.fn put(url: string, body: string, contentType: string) -> HttpResponse— Sends a PUT request with a body of the given Content-Type.fn patch(url: string, body: string, contentType: string) -> HttpResponse— Sends a PATCH request with a body of the given Content-Type.fn postJson(url: string, value: JsonValue) -> HttpResponse— Sends a POST request with a JSON body.fn putJson(url: string, value: JsonValue) -> HttpResponse— Sends a PUT request with a JSON body.fn patchJson(url: string, value: JsonValue) -> HttpResponse— Sends a PATCH request with a JSON body.fn postForm(url: string, fields: HashMap<string, string>) -> HttpResponse— Sends a POST request with form fields (application/x-www-form-urlencoded).fn postForm(url: string, form: FormData) -> HttpResponse— Sends a form: multipart/form-data when it has files, else url-encoded.fn download(url: string, path: string) -> int— Downloadsurlinto the file atpath; NetError for a non-2xx status. Returns the number of bytes written.fn request(method: string, url: string, body: string, contentType: string) -> HttpResponse— Sends a request with a text body ("" for none).fn send(method: string, url: string, body: Bytes, contentType: string, extra: Headers) -> HttpResponse— Sends a request: any method, an optional body (null for none) and extra headers for this request only (null for none). Follows redirects. Throws NetError (or TimeoutError) when the server cannot be reached or answers garbage; any status, including 4xx and 5xx, is returned as a response.