title: How to send multipart POST request using HttpURLConnection in java?
body: <p>It's my first time sending multipart requests and after digging here, I got even more confused so any help regarding the "correct" way will be very appriciated.</p>
  
  <p>I have a function, that should get : file path and a String representation of JSON and send POST request to the server using multipart.</p>
  
  <p>I'm not sure when to use the <code>boundary</code> and <code>"multipart/form-data"</code> content type, and the difference between <code>addPart</code> and <code>addTextBody</code>, and when (or why) it is always written <code>Content-Disposition: form-data; name=\</code></p>
  
  <pre><code>public String foo(String filePath, String jsonRep, Proxy proxy)
  {
     File f = new File(filePath);
     HttpURLConnection connection;
     connection = (HttpURLConnection) url.openConnection(proxy);
     connection.setRequestProperty("Content-Type", "multipart/form-data"); // How should I generate boundary? Should it be added here? 
  
      if (myMethod == "POST")
       {
         connection.getOutputStream().write( ? Both the json string and the file bytes?? );
        }
  
  
   .... checking there is no error code etc..
  
   return ReadResponse(connection) // read input stream..
  </code></pre>
  
  <p>Now I'm not sure how to continue, and how to write the file and the json string
  I saw this code:</p>
  
  <pre><code>MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  builder.addPart("upfile", fileBody);
  builder.addPart("text1", stringBody1);
  builder.addPart("text2", stringBody2);
  </code></pre>
  
  <p>But I can't seem to understand how it is connected to my <code>connection</code>.</p>
  
  <p>Can you please help?</p>