|
| 1 | +; |
| 2 | +; Copyright 2018 Thunderberry. |
| 3 | +; |
| 4 | +; Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +; you may not use this file except in compliance with the License. |
| 6 | +; You may obtain a copy of the License at |
| 7 | +; |
| 8 | +; https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +; |
| 10 | +; Unless required by applicable law or agreed to in writing, software |
| 11 | +; distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +; See the License for the specific language governing permissions and |
| 14 | +; limitations under the License. |
| 15 | +; |
| 16 | + |
| 17 | +(ns nl.altindag.client.service.ClojureHttpClientService |
| 18 | + (:gen-class) |
| 19 | + (:import |
| 20 | + [nl.altindag.client.service RequestService] |
| 21 | + [nl.altindag.client.model ClientResponse] |
| 22 | + [nl.altindag.client ClientType Constants ClientException] |
| 23 | + [nl.altindag.ssl SSLFactory] |
| 24 | + [java.net URL HttpURLConnection] |
| 25 | + [java.nio.charset StandardCharsets] |
| 26 | + [javax.net.ssl HttpsURLConnection] |
| 27 | + [org.apache.commons.io IOUtils] |
| 28 | + [org.apache.http.client.methods HttpGet])) |
| 29 | + |
| 30 | +(defn reify-request-service |
| 31 | + [^SSLFactory ssl-factory] |
| 32 | + (reify |
| 33 | + RequestService |
| 34 | + (executeRequest [this url] |
| 35 | + (let [connection (if (.contains url "https:") |
| 36 | + (doto ^HttpsURLConnection (cast HttpsURLConnection (.openConnection (URL. url))) |
| 37 | + (.setHostnameVerifier (.getHostnameVerifier ssl-factory)) |
| 38 | + (.setSSLSocketFactory (.getSslSocketFactory ssl-factory))) |
| 39 | + (if (.contains url "http:") |
| 40 | + (cast HttpURLConnection (.openConnection (URL. url))) |
| 41 | + (throw (ClientException. "Could not create a http client for one of these reasons: invalid url, security is enable while using an url with http or security is disable while using an url with https"))))] |
| 42 | + (.setRequestMethod connection HttpGet/METHOD_NAME) |
| 43 | + (.setRequestProperty connection Constants/HEADER_KEY_CLIENT_TYPE (.getValue (.getClientType this))) |
| 44 | + (ClientResponse. (IOUtils/toString (.getInputStream connection) StandardCharsets/UTF_8) |
| 45 | + (.getResponseCode connection)))) |
| 46 | + (getClientType [this] |
| 47 | + ClientType/CLOJURE_HTTP_CLIENT))) |
0 commit comments