In postman I post form data to an API built on play2 framework. Now I want to make this same call in another API build on play2 framework.
ws.url(url).setContentType("application/x-www-form-urlencoded")
.post("key1=value1&key2=value2");
can be used to submit form data but how do I add a file to the same request?
Using play framework 2.4.X
In the play website, you can find the following code to implement what you want. Note that the document is for play version of 2.5.X
import play.mvc.Http.MultipartFormData.*;
//the file you want to post
Source<ByteString, ?> file = FileIO.fromFile(new File("hello.txt"));
//generate the right format for posting
FilePart<Source<ByteString, ?>> fp = new FilePart<>("hello", "hello.txt", "text/plain", file);
DataPart dp = new DataPart("key", "value");// the data you want to post
ws.url(url).post(Source.from(Arrays.asList(fp, dp)));
update:
The first thing you should know is that ws
is built on com.ning.http.AsyncHttpClient
. As referred to Play Document,
the ws
of play 2.4.*
does not support multi part form upload directly. You can use the underlying client AsyncHttpClient
with RequestBuilder.addBodyPart. The following code can fulfillment what you want
import com.ning.http.client.AsyncHttpClient
import com.ning.http.client.multipart.FilePart
AsyncHttpClient myClient = ws.getUnderlying();
FilePart myFilePart = new FilePart("myFile", new java.io.File("test.txt"))
myClient.preparePut("http://localhost:9000/index").addBodyPart(filePart).execute.get()
have a good luck