                                            HttpEntityEnclosingRequestBase)
            (org.apache.http.client.params CookiePolicy ClientPNames)
            (org.apache.http.conn ClientConnectionManager)
+           (org.apache.http.conn.routing HttpRoute)
            (org.apache.http.conn.params ConnRoutePNames)
            (org.apache.http.impl.client DefaultHttpClient)
-           (org.apache.http.impl.conn SingleClientConnManager)
+           (org.apache.http.impl.conn SingleClientConnManager ProxySelectorRoutePlanner)
+
            (org.apache.http.util EntityUtils)))
 
 (defn parse-headers

         (retryRequest [e cnt context]
           (retry-handler e cnt context)))))
    (add-client-params! http-client scheme socket-timeout
                        conn-timeout server-name proxy-host proxy-port)
    (let [http-url (str scheme "://" server-name
                        (when server-port (str ":" server-port))
                        uri
                        (when query-string (str "?" query-string)))
          req (assoc req :http-url http-url)
          #^HttpRequest http-req (http-request-for request-method http-url)]
      (when response-interceptor
        (.addResponseInterceptor
         http-client


(def ^{:dynamic true} *cookie-store* nil)

(defn- with-routing
  "Use ProxySelectorRoutePlanner to choose proxy sensible based on http.nonProxyHosts"
  [client]
  (.setRoutePlanner client
                    (ProxySelectorRoutePlanner.
                     (.. client getConnectionManager getSchemeRegistry) nil))
  client)

(defn maybe-force-proxy [client request proxy-host proxy-port]
  (let [uri (.getURI request)]
    (when (and (nil? (#{"localhost" "127.0.0.1"} (.getHost uri))) proxy-host)
      (let [target (HttpHost. (.getHost uri) (.getPort uri) (.getScheme uri))]
        (set-client-param client ConnRoutePNames/FORCED_ROUTE
                          (HttpRoute. target nil (HttpHost. proxy-host proxy-port)
                                      (.. client getConnectionManager getSchemeRegistry
                                          (getScheme target) isLayered)))))
    request))

(defn add-client-params!
  "Add various client params to the http-client object, if needed."
  [http-client scheme socket-timeout conn-timeout server-name]
  (doto http-client
    (set-client-param ClientPNames/COOKIE_POLICY
                      CookiePolicy/BROWSER_COMPATIBILITY)
