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");
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.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import play.libs.WS;
import com.ning.http.multipart.FilePart;
import com.ning.http.multipart.MultipartRequestEntity;
import com.ning.http.multipart.Part;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// Build up the Multiparts
List<Part> parts = new ArrayList<>();
parts.add(new FilePart("file", new File(filename)));
Part[] partsA = parts.toArray(new Part[parts.size()]);
// Add it to the MultipartRequestEntity
MultipartRequestEntity reqE = new MultipartRequestEntity(partsA, null);
reqE.writeRequest(bos);
InputStream reqIS = new ByteArrayInputStream(bos.toByteArray());
WS.WSRequestHolder req = WS.url(InterchangeConfig.conflateUrl+"dataset")
.setContentType(reqE.getContentType());
req.post(reqIS).map(...);
// or req.post(reqIS).get();
This is all using pieces already in the Play 2.0 framework.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With