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

后端 未结 6 1307
小蘑菇
小蘑菇 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:27

    The only solution for now, without relying to external libraries, seems to be creating the Multipart Form Data request manually. This is an example how it can be done, using play.libs.WS.url:

    WSRequestHolder wsRequestHolder = WS.url(URL);
    
    String boundary = "--XYZ123--";
    
    String body = "";
    for (String key : data.keySet()) {
      body += "--" + boundary + "\r\n"
           + "Content-Disposition: form-data; name=\""
           + key + "\"\r\n\r\n"
           + data.get(key) + "\r\n";
    }
    body += "--" + boundary + "--";
    
    wsRequestHolder.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    wsRequestHolder.setHeader("Content-length", String.valueOf(body.length()));
    
    wsRequestHolder.post(body);
    

    data would be a java.util.Map containing all the name/value pairs you want to pass as form parameters. randomString is a randomized value to make the boundary change from request to request. Adding binary data would work the same way.

    This http://www.htmlcodetutorial.com/forms/form_enctype.html is a good place to refer to for understanding the specs.

提交回复
热议问题