Clojure building of URL from constituent parts

Viewed 8887

In Python I would do the following:

>>> q = urllib.urlencode({"q": "clojure url"})
>>> q
'q=clojure+url'

>>> url = "http://stackoverflow.com/search?" + q
>>> url
'http://stackoverflow.com/search?q=clojure+url'

How do I do all the encoding that's done for me above in Clojure? In other words, how do I do something akin to the following:

=> (build-url "http://stackoverflow.com/search" {"q" "clojure url"})
"http://stackoverflow.com/search?q=clojure+url"
6 Answers

This is the exact REPL equivalent of your python session, using clj-http.

user=> (require ['clj-http.client :as 'client])
nil
user=> (str "http://stackoverflow.com/search?"
user=*      (client/generate-query-string {"q" "clojure url"}))
"http://stackoverflow.com/search?q=clojure+url"

but clj-http makes it even easier:

user=> (client/get "http://stackoverflow.com/search?"
user=*             {:query-params {"q" "clojure url"}})
... <a lot of output, omitted to protect the innocent>...

assuming that you want to perform a GET request, that is.

Related