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"
clj-apache-http is pretty useful. With it you can do the following:
There is a
url-encode
function in Ring'sring.util.codec
namespace:I'm not sure if there's a prepackaged function to turn a map into a query string, but perhaps this could do the job:
An example:
All that remains is concatenating the result onto the end of a URL:
Seems to work:
Update:
Perhaps a modified version might make for a more Clojure-friendly experience. Also handles encoding via a Ring-style optional argument with utf-8 as default.
So now we can do
A simple solution using str(ings):
Here's one way:
I know this is not exactly the same as your Python snippet though. Please see the following post from the Clojure mailing list for a more complete answer:
http://www.mail-archive.com/clojure@googlegroups.com/msg29338.html
The code from there will allow you to do this:
This is the exact REPL equivalent of your python session, using clj-http.
but clj-http makes it even easier:
assuming that you want to perform a GET request, that is.