Reference Manual | Prev: Chapter 9. Data Caching and Performance | Next: Chapter 11. Proxy Server
CL-HTTP includes a full-featured programmatic HTTP client for making requests from Lisp. The client supports all standard HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE), persistent connections, chunked transfer encoding, automatic redirect handling, client-side authentication (basic and digest), SSL/TLS via HTTPS, and HTTP/2 with ALPN negotiation.
The client is built on two layers:
http:with-http-request —
provides full control over request headers, request bodies, and response
processing through lexical variables bound within the response body.
http:show-url,
http:post-url, http:put-url,
http:delete-url, and related convenience functions that build
on with-http-request with automatic redirect handling,
authentication, and display dispatch.
| Variable | Purpose |
|---|---|
http:*client-http-version* |
Controls the HTTP version advertised in request lines.
Default is :HTTP/1.1. HTTP/2 is negotiated via ALPN
during TLS handshake, not in the request line. |
http:*client-timeout* |
Maximum idle time (in 60ths of a second) before a client request times out. Default is 1800 (30 minutes). |
http:*trace-client* |
When non-nil, traces client activity. Set to T for
full tracing or :headers for header-only tracing. |
http:*debug-client* |
When non-nil, enables client debugging output. |
| File | Contents |
|---|---|
http:client;variables |
Client variables and parameters |
http:client;connection |
Connection management and pooling |
http:client;client |
Client class hierarchy, invoke-http-service,
with-http-request |
http:client;sexp-browser |
High-level functions: show-url, post-url,
put-url, delete-url |
http:client;authentication |
Client-side authentication (basic, digest) |
http:client;proxy |
Client proxy mapping and upstream proxy support |
http:client;http2 |
Portable HTTP/2 client: stream class, header bridging, response dispatch |
http:show-url is the simplest way to fetch and display a
URL. It performs a GET request, handles redirects and authentication
automatically, and dispatches the response body to a display
method based on the MIME content type.
;; Fetch and display a URL on *standard-output*
(http:show-url "http://www.example.com/")
;; Fetch with custom output stream
(http:show-url "http://www.example.com/" :stream my-stream)
;; Pass additional request headers
(http:show-url "http://www.example.com/"
:headers '(:accept ((:text :html))))
http:show-raw-url fetches a URL and displays the raw
response including status code, HTTP version, and all response headers,
followed by the body. Useful for debugging.
;; Display raw response with status, headers, and body
(http:show-raw-url "http://www.example.com/page.html")
;; Request a byte range
(http:show-raw-url "http://www.example.com/large-file.dat"
:start 0 :end 1023)
http:show-url-headers performs a HEAD request and displays
only the response headers, without fetching the body.
(http:show-url-headers "http://www.example.com/page.html")
http:capture-raw-url fetches a URL and returns its content
as a byte vector, along with the response header alist. This is the
preferred function for programmatic access to URL content.
;; Capture URL content as a byte vector
(multiple-value-bind (vector header-alist)
(http:capture-raw-url "http://www.example.com/data.json")
(format t "~&Received ~D bytes" (length vector))
(format t "~&Content-Type: ~A" (assoc :content-type header-alist)))
For full control, use http:with-http-request directly.
Within the response body, three lexical variables are bound:
client — the http:client object
remote-stream — the HTTP stream to the server
http-version — the negotiated HTTP version keyword
Keyword arguments:
:request-headers
:request-body
client,
remote-stream, and http-version bound to
write the request body. Output is automatically forced on
remote-stream.
:http-version
http:*client-http-version*.
:auto-transfer-decoding
:chunked
is the only registered decoder. Active only on HTTP/1.1 —
ignored on HTTP/1.0 (no chunking) and a no-op on HTTP/2 (chunking
is forbidden by RFC 9113 §8.2.2; bodies frame on END_STREAM).
See §10.2.6 for the convention used inside the response body
when chunked decoding is active.
;; Low-level GET with custom response processing
(http:with-http-request ("http://www.example.com/" :get
:request-headers '(:accept ((:application :json))))
(let ((status (http:client-status client)))
(cond ((eql status 200)
(http:with-transfer-decoding* (remote-stream url http-version
:headers http:*headers*)
;; Process the response body from remote-stream
(loop for line = (read-line remote-stream nil nil)
while line
do (format t "~&~A" line))))
(t (format t "~&Error: ~D" status)))))
HTTP/1.1 servers commonly return chunked responses (no
Content-Length) for dynamic content. The
:auto-transfer-decoding keyword tells
with-http-request to wrap the response body in the
appropriate decoder for the listed encodings. The registry
http::*transfer-decoder-alist* maps each encoding keyword
to a body wrapper; :chunked uses
http:with-chunked-transfer-decoding. Unknown encodings
signal an error at macroexpansion time.
;; Fetch a chunked HTTP/1.1 response, drain to a string
(http:with-http-request ("http://example.com/api/feed" :get
:auto-transfer-decoding '(:chunked))
(let ((sink (make-string-output-stream)))
(handler-case
(loop for c = (read-char remote-stream nil nil) while c
do (write-char c sink))
(www-utils:end-of-chunk-transfer-decoding () nil))
(get-output-stream-string sink)))
Stream-EOF convention. When the chunked stream reaches the
last chunk, the LispWorks, SBCL, and Genera ports signal
www-utils:end-of-chunk-transfer-decoding (a subclass of
end-of-file) directly from the read primitives,
regardless of the caller's eof-error-p argument. Code
that drains the stream with read-char,
read-byte, or read-sequence must wrap its
read loop in a local
(handler-case ... (www-utils:end-of-chunk-transfer-decoding () nil))
so the body returns its value normally. Higher-level helpers like
http::crlf-stream-copy-into-string handle this
internally.
http:post-url posts form data to a URL using URL-encoded
format (application/x-www-form-urlencoded). The form values
can be supplied as a property list, an alist of (keyword value) pairs, or a
pre-encoded byte vector.
;; Post form data as a property list
(http:post-url "http://www.example.com/search"
'(:query "Common Lisp" :max-results "10"))
;; Post form data as an alist
(http:post-url "http://www.example.com/login"
'((:username "admin") (:password "secret")))
http:post-form-values is a higher-level interface that
takes alternating keyword/value pairs as arguments. Values are transferred
using write-to-string with escape and base 10, and should be
recovered on the server side with http:bind-query-values*.
This allows Lisp objects to round-trip through form submission.
;; Post typed Lisp values
(http:post-form-values "http://www.example.com/api"
:name "John"
:count 42
:tags '(:web :lisp))
For custom POST requests with arbitrary content types, use
with-http-request with the :request-body
option. The request body form can access the lexical variables
client, remote-stream, and
http-version. Output is automatically forced on
remote-stream.
;; Post JSON data using with-http-request
(let ((json-data "{\"key\": \"value\"}"))
(http:with-http-request
("http://www.example.com/api" :post
:request-headers `(:content-type (:application :json)
:content-length ,(length json-data))
:request-body (write-string json-data remote-stream))
(let ((status (http:client-status client)))
(format t "~&Status: ~D ~A" status (http:client-reason client)))))
http:put-url uploads a resource to a URL. The resource
can be a pathname, a byte vector, or a writer function. Version conflict
checking is supported via the :version argument.
;; Put a file to a URL
(http:put-url "http://www.example.com/files/report.html"
#p"/tmp/report.html")
;; Put a byte vector
(http:put-url "http://www.example.com/files/data.bin"
my-byte-vector
:content-type '(:application :octet-stream))
;; Put with a writer function
(http:put-url "http://www.example.com/files/generated.txt"
#'(lambda (url stream)
(declare (ignore url))
(format stream "Generated at ~A" (get-universal-time)))
:content-type '(:text :plain))
;; Put with version conflict checking (If-Unmodified-Since)
(http:put-url "http://www.example.com/files/doc.html"
#p"/tmp/doc.html"
:version 3910000000) ; universal time of last known version
http:delete-url deletes a resource. Returns the URL and a
status keyword (:deleted or :accepted).
(multiple-value-bind (url status)
(http:delete-url "http://www.example.com/files/old-report.html")
(format t "~&~A: ~A" (url:name-string url) status))
http:show-url-trace sends a TRACE request, which asks the
server to echo the received request. Useful for diagnosing proxy chains.
The :max-forwards parameter limits how many proxies the
request traverses (default 5).
(http:show-url-trace "http://www.example.com/"
:max-forwards 3)
http:show-url-options sends an OPTIONS request, which
returns the communication options available for the target resource.
The response headers indicate allowed methods, authentication
requirements, and other capabilities.
(http:show-url-options "http://www.example.com/api/")
All high-level client functions accept either a URL string or an
interned url:http-url object. Strings are automatically
interned via url:intern-url.
;; Both forms are equivalent: (http:show-url "http://www.example.com/") (http:show-url (url:intern-url "http://www.example.com/"))
Request headers are specified as a property list using keyword/value
pairs. The function http:compute-standard-request-headers
builds a standard set of request headers including Host,
Accept, and User-Agent, with optional
authorization and byte-range headers.
;; Compute standard headers with custom Accept
(http:compute-standard-request-headers
(url:intern-url "http://www.example.com/")
:header-plist '(:accept ((:application :json))
:accept-language ((:en-us :q 1.0) (:en :q 0.8))))
For with-http-request, :request-headers
accepts either a header plist or a function. When a function, it is called
with (stream method http-version) and should write headers
directly to the stream using http:write-header.
Within the response body of with-http-request, the
special variable http:*headers* is bound to the parsed
response headers. Individual headers are accessed with
http:get-header.
(http:with-http-request ("http://www.example.com/" :get)
(let ((content-type (http:get-header :content-type))
(content-length (http:get-header :content-length))
(last-modified (http:get-header :last-modified))
(server (http:get-header :server)))
(format t "~&Content-Type: ~S" content-type)
(format t "~&Content-Length: ~D" content-length)
(format t "~&Last-Modified: ~A" last-modified)
(format t "~&Server: ~A" server)))
The display generic function dispatches on the MIME
content type of the response. It is specialized on
(url major-type minor-type remote-stream local-stream).
The high-level functions (show-url, etc.) call
display automatically. Custom display methods can be
defined for application-specific content types.
;; Define a custom display method for JSON
(defmethod http:display ((url url:http-url)
(major-type (eql :application))
(minor-type (eql :json))
remote-stream local-stream)
(fresh-line local-stream)
(http:with-transfer-decoding* (remote-stream url http:http-version
:headers http:*headers*)
(loop for line = (read-line remote-stream nil nil)
while line
do (write-line line local-stream))))
The macro http:with-status-code-dispatch provides
structured handling of HTTP response status codes. It automatically
handles redirects (301, 302, 303), authentication challenges (401),
and signals appropriate conditions for other error codes.
(http:with-http-request ("http://www.example.com/" :get
:request-headers (http:compute-standard-request-headers url))
(http:with-status-code-dispatch (:client client :url url
:success-status-codes (200 203))
;; This body executes only for success status codes
(format t "~&Success: ~D bytes"
(http:get-header :content-length))))
The client supports automatic authentication retry for HTTP Basic
and Digest authentication. The macro handling-authentication
wraps a request body and intercepts 401 (Unauthorized) responses.
When a 401 is received, the user is prompted for credentials (or they
are looked up in a credential cache), and the request is retried with
an Authorization header.
The high-level functions (show-url, post-url,
etc.) all use handling-authentication internally, so
authentication is handled transparently.
;; Automatic authentication is built into show-url
(http:show-url "http://www.example.com/protected/")
;; If the server responds with 401, the user will be prompted
;; Explicit credentials via request headers
(http:show-url "http://www.example.com/protected/"
:headers `(:authorization (:basic ,(http:encode-authorization
"username" "password"))))
When accessing URLs through an upstream proxy that requires
authentication, the client handles 407 (Proxy Authentication Required)
responses automatically. Proxy credentials are supplied via the
:proxy-authorization header or prompted interactively.
The client connects to HTTPS URLs transparently when SSL/TLS support
is available (indicated by the :cl-http-ssl-client feature
flag). No special API is needed — simply use an
https:// URL.
;; HTTPS requests work transparently
(http:show-url "https://www.example.com/")
(http:with-http-request ("https://api.example.com/data" :get
:request-headers '(:accept ((:application :json))))
(format t "~&Status: ~D" (http:client-status client)))
The SSL/TLS implementation is platform-specific:
comm SSL support
(OpenSSL-based).
The SBCL HTTPS client defaults to
+VERIFY-REQUIRED+: the server's certificate chain is
validated against the system CA bundle (pure-tls loads it
automatically) and the handshake fails if validation fails. This is
the safe default for production outbound HTTPS.
For testing against servers with self-signed or untrusted
certificates, supply a less strict verify mode through the SSL
context used by http:%make-ssl-client-context, or supply
your own trust store via the pure-tls configuration. Do not relax
verification globally on production servers.
For CL-HTTP ports without SSL/TLS, an upstream SSL proxy such as
mitmproxy or another CL-HTTP
instance acting as a forward proxy can provide HTTPS access.
Configure this with http:define-client-proxy-mapping
(see Chapter 11) — an HTTPS-fronted
proxy is supported via the http:https-proxy class (see
§10.9.4).
CL-HTTP supports HTTP/2 client connections on LispWorks and SBCL. HTTP/2
is negotiated transparently via ALPN (Application-Layer Protocol
Negotiation) during the TLS handshake — no changes to client code
are required. The *client-http-version* variable controls only
the HTTP/1.x request line version; HTTP/2 negotiation is independent.
When connecting to an HTTPS URL, the client offers both
h2 (HTTP/2) and http/1.1 in the TLS ALPN
extension. If the server selects h2, the client
automatically uses HTTP/2 framing for the request. The result is
returned to the caller through the same with-http-request
interface.
After the first connection to a host, the negotiated protocol version is cached. Subsequent connections to the same host reuse the cached version, avoiding redundant ALPN negotiation. The cache entries expire based on connection idle time.
The HTTP/2 client uses a reactor architecture with a single connection
per host multiplexing concurrent streams. The portable code in
http:client;http2 defines:
http2-client-stream — HTTP/2 client stream class
that collects response headers and body
Platform-specific code defines the connection class, reactor loop,
ALPN negotiation, connection pool, and the %open-h2-client-connection
and %h2-invoke-http-service functions.
;; HTTP/2 is used automatically for HTTPS when available
(http:show-url "https://www.example.com/")
;; Check which version was negotiated
(http:with-http-request ("https://www.example.com/" :get)
(format t "~&Protocol: ~A" http-version))
The client maintains persistent (keep-alive) HTTP connections for HTTP/1.1 servers. Multiple requests to the same host:port reuse the same TCP connection, amortizing the cost of TCP and TLS handshakes. The connection pool is managed automatically.
The variable http:*client-persistent-connections* controls
whether persistent connections are used. Connection reuse is governed by
response headers (Connection: close forces a new connection)
and idle timeout.
The macro http:handling-redirects wraps a request body and
automatically retries on 301 (Moved Permanently), 302 (Moved Temporarily),
and 303 (See Other) responses, following the redirect chain up to a
configurable limit.
;; Default maximum redirects is 5
http:*maximum-redirects* ;=> 5
;; Custom redirect limit
(http:handling-redirects (url 10)
(http:with-http-request (url :get)
(format t "~&Final URL: ~A" (url:name-string (http:client-url client)))))
The invoke-http-service :around method
wraps all requests with with-network-failure-retries, which
automatically retries on transient network failures (connection reset,
timeout on initial connect). This is transparent to the caller.
The client supports upstream proxy connections for protocols that may
not be directly reachable. Use http:define-client-proxy-mapping
to configure proxy routing.
;; Route HTTPS through a local proxy
(http:define-client-proxy-mapping
:standard-proxies ((:https :default "localhost" 8080))
:url-mappings (("Null-Proxy" 0 "http://localhost/" 8002)))
The :standard-proxies argument specifies default proxies
per protocol and port. Each entry is (protocol port proxy-host
proxy-port). Use :default as the port to match all
ports for that protocol.
The :url-mappings argument specifies direct-access
exceptions and per-URL proxy overrides. A "Null-Proxy" entry
with port 0 indicates that matching URLs should be accessed directly
without a proxy.
Some forward proxies listen on HTTPS rather than plain HTTP —
the client opens a TLS leg to the proxy and writes absolute-URI requests
inside it (identical to curl --proxy https://...). CL-HTTP
models this with an http:https-proxy subclass of
http:http-proxy. The http:proxy-scheme
generic returns :http for an
http-proxy and :https for an
https-proxy; the client uses that scheme to decide whether
to open TCP or TLS to the proxy, independent of the origin URL's
scheme.
http:intern-proxy takes a :scheme keyword
(default :http for backward compatibility):
;; Plain HTTP forward proxy (default scheme :http) (http:intern-proxy "proxy.example.com" 8080) ;; HTTPS-fronted forward proxy (http:intern-proxy "secure-proxy.example.com" 8443 :scheme :https)
The variable http:*proxy-class* is an alist mapping
proxy scheme to class — default
((:http . http-proxy) (:https . https-proxy)). Override
either entry to substitute a custom subclass.
Plain http-proxy objects continue to bridge HTTPS
origins via absolute-URI in the :http path (the proxy then
opens TLS to the origin on the client's behalf). Use an
https-proxy only when the proxy itself is reached over
TLS.
The http:client class encapsulates a single HTTP
transaction. It records the URL, method, connection, request/response
headers, status code, timing information, and logging data. Key
accessors:
| Accessor | Returns |
|---|---|
http:client-url |
The request URL object |
http:client-method |
The HTTP method keyword (:get, :post, etc.) |
http:client-status |
The response status code (integer) |
http:client-reason |
The response reason string |
http:client-connection-version |
The HTTP version keyword of the server |
http:client-request-version |
The actual HTTP version used in the transaction |
http:client-response-headers |
The raw response headers |
http:client-stream |
The HTTP stream to the remote server |
Reference Manual | Prev: Chapter 9. Data Caching and Performance | Next: Chapter 11. Proxy Server