In Java Http request, we can do this to make multipart HTTP POST.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
How could I achieve the same using WS.url or WS.WSRequest?
WSRequestHolder wsReq = WS.url("http//url");
wsReq.setHeader("Content-type", "multipart/form-data");
The accepted answer didn't work with play 2.5. Also the answer in play 2.6 documentation didn't work for 2.5.
The below worked fine:
For
mat
andapp
objects they are obtained when inheritingplay.test.WithApplication
class.Working example for play 2.3 using above approach, also added contentType while uploading the file.
As Romain Sertelon suggested, you can write a Writeable to handle this case. Here's one I wrote:
Here's how to use it:
It seems, based on play API documentation, that there is no built-in for multipart POST bodies.
However, it may be possible to create your own multipart body using the method
with a type T of your choice, and the corresponding Writeable and ContentTypeOf types too.
But this would imply digging in how multipart bodies work with HTTP.
The only solution for now, without relying to external libraries, seems to be creating the Multipart Form Data request manually. This is an example how it can be done, using
play.libs.WS.url
:data
would be ajava.util.Map<String, String>
containing all the name/value pairs you want to pass as form parameters.randomString
is a randomized value to make the boundary change from request to request. Adding binary data would work the same way.This http://www.htmlcodetutorial.com/forms/form_enctype.html is a good place to refer to for understanding the specs.
This is sloppy, and can definitely be cleaned up, but here's what I did to get it working. Feel free to make this so much better.
This is all using pieces already in the Play 2.0 framework.