0

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

Anirudh
  • 15,107
  • 2
  • 14
  • 26
  • Are you trying to submit form data AND file in the same request? Or you just want to submit a file? – Salem May 27 '16 at 13:37
  • "trying to submit form data AND file in the same request" - yes. justlike in postman for example – Anirudh May 27 '16 at 15:39

1 Answers1

1

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

Jerry
  • 492
  • 4
  • 8
  • the `ws` of play 2.4.x does not support multi part form upload, but you can fulfill this function with the help of `AsyncHttpClient`. I have update the answer and I have tried it with scala, it works – Jerry May 28 '16 at 10:06