Clojure:
Sending an HTTP request
How to:
In Clojure, you can send HTTP requests using the clj-http
client.
First, add the dependency to your project.clj
:
[clj-http "3.12.3"]
Now, let’s send a GET request:
(require '[clj-http.client :as client])
(let [response (client/get "http://httpbin.org/get")]
(println response))
Output sample:
{:status 200, :headers {...}, :body "..."}
To post data:
(let [response (client/post "http://httpbin.org/post" {:form-params {:key "value"}})]
(println response))
Deep Dive
Sending HTTP requests isn’t new. It’s as old as the web itself. Clojure, being a modern Lisp, has several libs to make HTTP requests. clj-http
is a popular one, but others like http-kit
or Clojure’s core clj-http.client
exist.
clj-http
leans on the Apache HttpComponents Client for Java under the hood. It’s versatile but can feel Java-heavy. An alternative, http-kit
, is more lightweight and Clojure-idiomatic but less feature-rich.
When you send HTTP requests, you’re doing so over TCP/IP, which frames your requests according to a well-established protocol. This universal standard lets you interact with practically any web service out there.
See Also
clj-http
GitHub repository: https://github.com/dakrone/clj-http- Official Clojure site: https://clojure.org
- HttpComponents Client documentation: https://hc.apache.org/httpcomponents-client-ga/
- For real-time needs, consider
http-kit
: http://www.http-kit.org