Chapter 5. Network I/O and Web Services
5.0. Introduction
More and more these days, it seems like every system we build has to talk to something, somewhere.[16] We’d hardly be doing anything if we didn’t actually talk with some other computers over some kind of network.
This chapter covers all of the normal remote communication modes you would expect—HTTP, TCP, UDP, and the like—as well as some relative newcomers[17] like message-oriented architectures.
5.1. Making HTTP Requests
Problem
You want to make a simple HTTP GET or POST request.
Solution
Use slurp
to make simple HTTP GET requests:
(
slurp
"http://example.com"
)
;; -> "<!doctype html>\n<html>\n<head>\n <title>Example Domain</title> ...
Use the clj-http
library to make GET, POST, and other requests with
specific parameters or headers, to handle redirects and other special
circumstances, or to get specific details about the response.
To follow along, add [clj-http "0.7.7"]
to your project’s
dependencies, or use lein-try
to start a REPL:
$ lein try clj-http
Use clj-http.client/get
to make GET requests:
(
require
'
[
clj-http.client
:as
http
])
(
:status
(
http/get
"http://clojure.org"
))
;; -> 200
(
->
(
http/get
"http://clojure.org"
)
:headers
(
get
"server"
))
;; -> "nginx"
(
->
(
http/get
"http://www.amazon.com/"
)
:cookies
keys
)
;; -> ("session-id" "session-id-time" "x-wl-uid" "skin")
Parameters can be included in both GET and POST requests. Use
clj-http.client/post
to make POST requests:
(
http/get
"http://google.com/"
{
:query-params ...
Get Clojure Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.