Play 2.0 How to Post MultipartFormData using WS.url or WS.WSRequest

后端 未结 6 1316
小蘑菇
小蘑菇 2021-02-08 22:42

In Java Http request, we can do this to make multipart HTTP POST.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

FileBo         


        
6条回答
  •  悲哀的现实
    2021-02-08 23:42

    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 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.

提交回复
热议问题