我正在寻找一种更地道的方式,如果可能的话,习惯的方法来写下面的Clojure代码:编写.NET互操作功能
(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
)
这是ClojureCLR和作品。 (事实上,它的CLR变种没多大关系)
我想摆脱DEFS的(通过更换让?他们可以称呼对方?)
如何更好的方法要注意流 - 请记住,链接不起作用,因为我需要稍后关闭流。
编辑:在答案后,我发现在.NET中使用WebClient类下载网页的简单方法。我还使用了许多的米哈尔商推荐的方法 - 只是想记录一下我现在认为是最好的答案:
(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)))