I am looking for a more idiomatic way, if possible, to write the following clojure code:
(import '(System.Net HttpWebRequest NetworkCredential) '(System.IO StreamReader)) (defn downloadWebPage "Downloads the webpage at the given url and returns its contents." [^String url ^String user ^String password] (def req (HttpWebRequest/Create url)) (.set_Credentials req (NetworkCredential. user password "")) (.set_UserAgent req ".NET") (def res (.GetResponse req)) (def responsestr (.GetResponseStream res)) (def rdr (StreamReader. responsestr)) (def content (.ReadToEnd rdr)) (.Close rdr) (.Close responsestr) (.Close res) content )
It works on ClojureCLR and it works. (the fact that this is a variant of the CLR doesn't really matter)
I would like to get rid of defs (replace with let? Can they refer to each other?)
What about a better way to get to the thread - bearing in mind that .. the chain is not working because I need to close the threads later.
EDIT: after the answer, I found a much simpler way in .NET to load a web page using the WebClient class. I still used many approaches recommended by Michal - I just wanted to write down what I consider to be the best answer:
(defn download-web-page "Downloads the webpage at the given url and returns its contents." [^String url ^String user ^String password] (with-open [client (doto (WebClient.) (.set_Credentials (NetworkCredential. user password "")))] (.DownloadString client url)))
clojure clojureclr
Kurt schelfthout
source share