From 994411d27e8b7e5ab1dddbf1d053b701e20467bd Mon Sep 17 00:00:00 2001 From: Oliver Hine Date: Wed, 22 Apr 2015 10:45:41 +0100 Subject: [PATCH] Preventing NPE on decode-body-headers when body is nil (e.g. HEAD request) --- README.org | 2 ++ src/clj_http/client.clj | 16 +++++++--------- test/clj_http/test/client.clj | 6 ++++-- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/README.org b/README.org index 2d547b29..f5457b76 100644 --- a/README.org +++ b/README.org @@ -387,6 +387,8 @@ from clj-http's dependencies without causing any problems like so: [clj-http "0.6.0" :exclusions [crouton]]]) #+END_SRC +Note also that HEAD requests will not return a body, in which case this setting will have no effect. + clj-http will automatically disable the =:decode-body-headers= option. ** Misc diff --git a/src/clj_http/client.clj b/src/clj_http/client.clj index dc003f4e..b13f8202 100644 --- a/src/clj_http/client.clj +++ b/src/clj_http/client.clj @@ -488,22 +488,20 @@ web page, adding them into the headers map of the response if any are found. Only looks at the body if the :decode-body-headers option is set to a truthy value. Will be silently disabled if crouton is excluded - from clj-http's dependencies." + from clj-http's dependencies. Will do nothing if no body is returned, e.g. HEAD requests" [client] (fn [req] - (if (opt req :decode-body-headers) - (if crouton-enabled? - (let [resp (client req) - body-bytes (util/force-byte-array (:body resp)) + (let [resp (client req)] + (if (and (opt req :decode-body-headers) crouton-enabled? (:body resp)) + (let [body-bytes (util/force-byte-array (:body resp)) body-stream1 (java.io.ByteArrayInputStream. body-bytes) body-map (parse-html body-stream1) additional-headers (get-headers-from-body body-map) body-stream2 (java.io.ByteArrayInputStream. body-bytes)] (assoc resp - :headers (merge (:headers resp) additional-headers) - :body body-stream2)) - (client req)) - (client req)))) + :headers (merge (:headers resp) additional-headers) + :body body-stream2)) + resp)))) (defn content-type-value [type] (if (keyword? type) diff --git a/test/clj_http/test/client.clj b/test/clj_http/test/client.clj index 7ec65742..5ed4a194 100644 --- a/test/clj_http/test/client.clj +++ b/test/clj_http/test/client.clj @@ -635,12 +635,14 @@ client (fn [req] {:body (.getBytes text)}) new-client (client/wrap-additional-header-parsing client) resp (new-client {:decode-body-headers true}) - resp2 (new-client {:decode-body-headers false})] + resp2 (new-client {:decode-body-headers false}) + resp3 ((client/wrap-additional-header-parsing (fn [req] {:body nil})) {:decode-body-headers true})] (is (= {"content-type" "text/html; charset=Shift_JIS" "content-style-type" "text/css" "content-script-type" "text/javascript"} (:headers resp))) - (is (nil? (:headers resp2))))) + (is (nil? (:headers resp2))) + (is (nil? (:headers resp3))))) (deftest t-wrap-additional-header-parsing-html5 (let [^String text (slurp (resource "header-html5-test.html"))