Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/clj_http/client.clj
Original file line number Diff line number Diff line change
Expand Up @@ -756,13 +756,22 @@
([req respond raise]
(client (accept-encoding-request req) respond raise))))

(defn- strip-quotes
"If s starts and ends with \", returns s with quotes stripped,
else returns it unchanged."
[^String s]
(if (and (.startsWith s "\"")
(.endsWith s "\""))
(subs s 1 (dec (count s)))
s))

(defn detect-charset
"Given a charset header, detect the charset, returns UTF-8 if not found."
[content-type]
(or
(when-let [found (when content-type
(re-find #"(?i)charset\s*=\s*([^\s]+)" content-type))]
(second found))
(strip-quotes (second found)))
"UTF-8"))

(defn- multi-param-entries [key values multi-param-style encoding]
Expand Down
18 changes: 9 additions & 9 deletions test/clj_http/test/client_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -1633,15 +1633,15 @@
client/wrap-request-timing))))

(deftest t-detect-charset-by-content-type
(is (= "UTF-8" (client/detect-charset nil)))
(is (= "UTF-8"(client/detect-charset "application/json")))
(is (= "UTF-8"(client/detect-charset "text/html")))
(is (= "GBK"(client/detect-charset "application/json; charset=GBK")))
(is (= "ISO-8859-1" (client/detect-charset
"application/json; charset=ISO-8859-1")))
(is (= "ISO-8859-1" (client/detect-charset
"application/json; charset = ISO-8859-1")))
(is (= "GB2312" (client/detect-charset "text/html; Charset=GB2312"))))
(are [content-type expected-charset] (= expected-charset (client/detect-charset content-type))
nil "UTF-8"
"application/json" "UTF-8"
"text/html" "UTF-8"
"application/json; charset=GBK" "GBK"
"application/json; charset=ISO-8859-1" "ISO-8859-1"
"application/json; charset = ISO-8859-1" "ISO-8859-1"
"text/html; Charset=GB2312" "GB2312"
"text/html; charset=\"ISO-8859-1\"" "ISO-8859-1"))

(deftest ^:integration customMethodTest
(run-server)
Expand Down