Created
November 8, 2013 09:53
-
-
Save adambard/7368785 to your computer and use it in GitHub Desktop.
Posting multipart/form-data messages with Content-Id headers (for cid: tags) in Clojure, using Jersey 1.17.1.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns multipart-test | |
(:import | |
javax.ws.rs.core.MediaType | |
com.sun.jersey.api.client.Client | |
com.sun.jersey.api.client.ClientResponse | |
com.sun.jersey.api.client.config.DefaultClientConfig | |
com.sun.jersey.api.client.filter.HTTPBasicAuthFilter | |
com.sun.jersey.multipart.FormDataMultiPart | |
com.sun.jersey.multipart.file.FileDataBodyPart | |
com.sun.jersey.multipart.impl.MultiPartWriter) | |
(:require | |
[taoensso.timbre :as logging])) | |
(defn to-s [s] | |
(cond | |
(coll? s) (clojure.string/join "," s) | |
:otherwise (str s))) | |
(defn multipart-client [] | |
(let [cc (DefaultClientConfig.)] | |
(-> cc (.getClasses) (.add MultiPartWriter)) | |
(Client/create cc))) | |
(defn wrap-basic-auth | |
"Set up basic auth on the client, if provided" | |
[client {:keys [basic-auth] :as req}] | |
(if basic-auth | |
(doto client | |
(.addFilter (HTTPBasicAuthFilter. (first basic-auth) (last basic-auth)))) | |
client)) | |
(defn wrap-form-multipart | |
"Add the form params to the provided form" | |
[form {:keys [form-params] :as req}] | |
(doseq [[k v] form-params | |
:when (not (nil? v))] | |
(logging/info k (to-s v)) | |
(.field form (name k) (to-s v))) | |
form) | |
(defn wrap-attachments | |
"Add the attachments to the provided form" | |
[form {:keys [attachment] :as req}] | |
(doseq [a attachment] | |
(do | |
(.bodyPart form | |
(FileDataBodyPart. (:name a) | |
(:content a) | |
(MediaType/valueOf (:mime-type a)))))) | |
form) | |
(defn post-multipart | |
"Create a multipart form post to the provide url, with | |
the provided basic-auth, form-params, and attachments" | |
[url {:keys [basic-auth form-params attachments] :as req}] | |
(let [client (wrap-basic-auth (multipart-client) req) | |
resource (.resource client url) | |
form (-> (FormDataMultiPart.) | |
(wrap-form-multipart req) | |
(wrap-attachments req))] | |
(-> resource | |
(.type MediaType/MULTIPART_FORM_DATA_TYPE) | |
(.post ClientResponse form)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment