【问题标题】:How can I set the User-Agent header when downloading a file in Clojure?在 Clojure 中下载文件时如何设置 User-Agent 标头?
【发布时间】:2019-09-25 01:48:06
【问题描述】:

使用this answer (clojure.java.io/input-stream) 中描述的方法,我将如何设置 User-Agent 请求标头?

【问题讨论】:

    标签: url clojure download io


    【解决方案1】:

    你不能。 clojure.java.io 是一个非常简单的 API,用于做最简单的事情。如果您想要任何真正的自定义,您需要使用真正的 HTTP 库。

    【讨论】:

      【解决方案2】:

      您可以,但只能在一定程度上设置属性。

      从这个答案https://stackoverflow.com/a/47300260/483566 我尝试在终端中运行 netcat:nc -l -p 8080

      在 REPL 上,我尝试了以下方法:

      $ lein repl
      nREPL server started on port 42819 on host 127.0.0.1 - nrepl://127.0.0.1:42819
      REPL-y 0.4.3, nREPL 0.6.0
      Clojure 1.10.0
      OpenJDK 64-Bit Server VM 11.0.4+11-post-Ubuntu-1ubuntu218.04.3
          Docs: (doc function-name-here)
                (find-doc "part-of-name-here")
        Source: (source function-name-here)
       Javadoc: (javadoc java-object-or-class-here)
          Exit: Control+D or (exit) or (quit)
       Results: Stored in vars *1, *2, *3, an exception in *e
      
      user=> (System/setProperty "http.agent" "Clojure REPL")
      nil
      user=> (slurp "http://localhost:8080/")
      

      Netcat 实际上并没有提供内容,因此 REPL 会阻塞,但是如果您看到运行 netcat 的终端,您会看到如下内容:

      GET / HTTP/1.1
      User-Agent: Clojure REPL Java/11.0.4
      Host: localhost:8080
      Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
      Connection: keep-alive
      

      对于实际的自定义,您可能希望使用一个 HTTP 客户端库来提供对 HTTP 标头的访问(大多数都会这样做)。

      【讨论】:

      • 谢谢!我在看clj-http。我来自 Python,几乎完全使用 requests,这看起来有点等价。
      • 这是一个很好的库。如果您正在寻找精选的库列表,可以查看clojure-toolbox.com
      猜你喜欢
      • 2014-05-03
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 2020-06-02
      相关资源
      最近更新 更多