title: How to upload a file by POST in JAVA
body: <p>I'm trying to upload a text file by using POST in JAVA.
  But the packet I'm sending is lacking the body with the file content.</p>
  
  <p>If i'm using POSTMAN chrome ext, I'm getting packet :</p>
  
  <pre><code>POST http://localhost:8080/storm-webapp/load-scripts/ HTTP/1.1
  Host: localhost:8080
  Connection: keep-alive
  Content-Length: 205
  Cache-Control: no-cache
  Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
  User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
  Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryq3Ss6jb9i23grqZA
  Accept: */*
  Accept-Encoding: gzip,deflate,sdch
  Accept-Language: en-US,en;q=0.8
  Cookie: CoreI18n=en-US
  
  ------WebKitFormBoundaryq3Ss6jb9i23grqZA
  Content-Disposition: form-data; name="file"; filename="HelloWorld.txt"
  Content-Type: text/plain
  
  This is a test text to upload
  ------WebKitFormBoundaryq3Ss6jb9i23grqZA--
  </code></pre>
  
  <p>In case and I'm creating the upload trough java code, I'm getting next raw :</p>
  
  <pre><code>POST http://localhost:8888/storm-webapp/load-scripts/ HTTP/1.1
  Content-Type: multipart/form-data; boundary=----13f7a4f68b9
  User-Agent: Java/1.7.0_17
  Host: localhost:8888
  Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
  Connection: keep-alive
  Content-Length: 0
  </code></pre>
  
  <p>As you see, I'm missing the entire part of the body...
  The code I'm using is :</p>
  
  <pre><code>    BufferedReader reader = null;
      File file = new File("HelloWorld.txt");
  
      String boundary = "WebKitFormBoundary" + Long.toHexString(System.currentTimeMillis());
      HttpURLConnection conn = (HttpURLConnection) new URL(rest).openConnection();
      /*************Header*****************/
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----" + boundary);
      /*********Body**************/
      PrintWriter writer = null;
      writer = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
      writer.println("------" + boundary);
      writer.println("Content-Disposition: form-data; name=\"file\"; filename=\"HelloWorld.txt\"");
      writer.println("Content-Type: text/plain");
      writer.println();
  
      reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
      for (String line; (line = reader.readLine()) != null;) {
          writer.println(line);
      }
      writer.println("------" + boundary + "--");
      /*******************************************************/
  
      reader.close();
  
      int responseCode = conn.getResponseCode();
  
      System.out.println("ResponseCode is : " + responseCode);
  </code></pre>
  
  <p>and the response code is 400 ...</p>
  
  <p>Any idea, what I'm doing wrong ?
  Thanks</p>