Search code examples
httpclojurex509certificate

Extract both certificates and response payload from URL with Clojure


I'm trying to extract both the certificate from an URL and its payload response in a single request. My code right now looks like this:

(s/defn get-server-leaf-certificate
  [url :- s/Str]
  (let [conn (.openConnection url)]
    (with-open [_ (.getInputStream conn)]
      (some-> (.getServerCertificates conn) first))))

With this implementation I can extract the certificate but how can I also extract the response from this request?


Solution

  • This is the way I got this to work:

    (:import (java.net URI)
               (java.io BufferedReader))
    
    (s/defn retrieve-dynamic-response-from-psp!
      [url :- s/Str]
      (let [conn (.openConnection (io/as-url url))
            _ (.setReadTimeout conn (config/read-timeout))
            _ (.setRequestProperty conn "Accept" "application/json")]
        (with-open [is (.getInputStream conn)]
          (let [response-code (.getResponseCode conn)
                certificate (some-> (.getServerCertificates conn) first)
                reader ^BufferedReader (io/reader is)
                raw-response-body (-> reader line-seq first)]
            (if-not (and (>= response-code 200) (< response-code 300))
              (throw "Error retrieving response")
              [raw-response-body certificate])))))