在邮递员中,我将表单数据发布到基于 play2 框架的 API。现在我想在另一个基于 play2 框架的 API 中进行同样的调用。
ws.url(url).setContentType("application/x-www-form-urlencoded")
.post("key1=value1&key2=value2");
可用于提交表单数据,但如何将文件添加到同一个请求?
使用播放框架 2.4.X
在邮递员中,我将表单数据发布到基于 play2 框架的 API。现在我想在另一个基于 play2 框架的 API 中进行同样的调用。
ws.url(url).setContentType("application/x-www-form-urlencoded")
.post("key1=value1&key2=value2");
可用于提交表单数据,但如何将文件添加到同一个请求?
使用播放框架 2.4.X
在play网站,你可以找到下面的代码来实现你想要的。请注意,该文档适用于 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)));
更新:
您应该知道的第一件事ws
是基于com.ning.http.AsyncHttpClient
. 参照Play Document,ws
不play 2.4.*
支持直接多部分表单上传。您可以将底层客户端AsyncHttpClient
与RequestBuilder.addBodyPart一起使用。以下代码可以满足您的需求
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()
祝你好运