Skip to content

Instantly share code, notes, and snippets.

@EECOLOR
Created November 25, 2013 21:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EECOLOR/7649144 to your computer and use it in GitHub Desktop.
Save EECOLOR/7649144 to your computer and use it in GitHub Desktop.
Multipart form data with Play Framework 2 WS client
//The following example allows you to post `multipart/form-data`. It is a simple version that only
//works with `String` values, but it could easily be modified to use other types of data.
type NameValuePair = (String, String)
case class MultipartFormData(elements: Seq[NameValuePair], boundary: String)(
implicit codec: Codec) {
private val HTTP_SEPARATOR = "\r\n"
private val actualBoundary = "--" + boundary
private val endBoundary = actualBoundary + "--" + HTTP_SEPARATOR
private val contentType = "multipart/form-data; boundary=" + boundary
private val content = elements.map(toPart).mkString + endBoundary
val body = Body(content)
case class Body(content: String)
object Body {
implicit val contentTypeOf:ContentTypeOf[Body] =
ContentTypeOf(Some(contentType))
implicit val writes: Writeable[Body] =
Writeable(body => codec.encode(body.content))
}
private def toPart(nameValuePair: NameValuePair) = {
val (name, value) = nameValuePair
actualBoundary + HTTP_SEPARATOR +
"Content-Disposition: form-data; name=\"" + name + "\"" + HTTP_SEPARATOR +
HTTP_SEPARATOR +
value + HTTP_SEPARATOR
}
}
//Usage is like this:
val data = MultipartFormData(formFields, "asdfghjkl123")
WS.url(myUrl).post(data.body)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment