title: POST file (as binary stream) using java.net.HttpURLConnection as a param file=<file binary stream>
body: <p>I am trying to upload (POST) a file to an endpoint using java.net.HttpURLConnection but I keep getting http code 400 (bad request).</p>
  
  <p>I refered to <a href="https://stackoverflow.com/questions/35839130/send-file-and-parameters-to-server-with-httpurlconnection-in-android-api-23">Send File And Parameters To Server With HttpURLConnection in android API 23</a></p>
  
  <p>but problem is that I need to send this file as request body param (file=).</p>
  
  <p>Note: The files will be of small size only (4-5mb) so I am reading it entirely in memory.</p>
  
  <p>Corresponding curl request is:</p>
  
  <p>curl -X POST "API" -H "Content-Type: multipart/form-data" -F "file="</p>
  
  <hr>
  
  <p>Excerpts of Code that I am using:</p>
  
  <pre><code>    Proxy webproxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(" 
                                  &lt;proxy host&gt;", &lt;proxy_port&gt;));
      HttpURLConnection http_conn = (HttpURLConnection) 
                                       url.openConnection(webproxy);
      String authorization = getAuthorization(access_token);
      http_conn.setRequestMethod("POST");
      http_conn.setRequestProperty("Accept-Charset", "UTF-8");        
      http_conn.setRequestProperty("Authorization", authorization);
      http_conn.setRequestProperty("Connection", "Keep-Alive");
      http_conn.setRequestProperty("Content-Type", "multipart/form-data);  
      http_conn.setDoOutput(true);
      http_conn.setDoInput(true);
      DataOutputStream outputStream;
      outputStream = new DataOutputStream(http_conn.getOutputStream());
      File file_obj = new File(this.file);                                
      byte[] allBytes = new byte[(int) file_obj.length()];
      FileInputStream fileInputStream = new FileInputStream(file_obj);                
      outputStream.write("file=".getBytes("UTF-8")); &lt;---Trying to add file param here
      fileInputStream.read(allBytes);
      outputStream.write(allBytes);
  </code></pre>
  
  <p>Post that I just read response using below piece of code (works fine for different GET requests):</p>
  
  <pre><code>    InputStream inputStream = http_conn.getInputStream();            
          BufferedReader bufferedReader = new BufferedReader(new 
      InputStreamReader(inputStream));
      String line = "";            
      while ((line = bufferedReader.readLine()) != null) {
          data = data + line;                
      }
  </code></pre>
  
  <p>Note: I use java rarely an am not very familiar with it so please be descriptive in your response.</p>