title: Android: java.lang.IllegalStateException: Already connected
body: <p>I'm testing a sample of code but its always error at <code>connection.setDoInput(true);</code></p>
  
  <pre><code>HttpsURLConnection connection = null;
  DataOutputStream outputStream = null;
  DataInputStream inputStream = null;
  
  String urlServer = "https://www.myurl.com/upload.php";
  String lineEnd = "\r\n";
  String twoHyphens = "--";
  String boundary = "*****";
  
  int bytesRead = 0;
  int bytesAvailable = 0;
  int bufferSize = 0;
  byte[] buffer = null;
  int maxBufferSize = 1*1024*1024;
  
  try {
      FileInputStream fileInputStream = new FileInputStream(new File(params[0]));
  
      URL url = new URL(urlServer);
  
      connection = (HttpsURLConnection) url.openConnection();
      connection.setConnectTimeout(1000);
  
      // Allow Inputs &amp; Outputs
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setUseCaches(false);
  
      // Enable POST method
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
  
      connection.setConnectTimeout(1000);
  
      outputStream = new DataOutputStream(connection.getOutputStream());
      outputStream.writeBytes(twoHyphens + boundary + lineEnd);
      outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + params[0] + "\"" + lineEnd);
      outputStream.writeBytes(lineEnd);
  
      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];
  
      // Read file
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  
      while (bytesRead &gt; 0) {
          outputStream.write(buffer, 0, bufferSize);
          bytesAvailable = fileInputStream.available();
          bufferSize = Math.min(bytesAvailable, maxBufferSize);
          bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      }
  
      outputStream.writeBytes(lineEnd);
      outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
  </code></pre>
  
  <p>The error log is <code>java.lang.IllegalStateException: Already connected</code>.
  I have tried these but none is working:</p>
  
  <pre><code>connection.setRequestProperty("Connection", "close");
  connection.disconnect();
  connection.setConnectTimeout(1000);
  </code></pre>
  
  <p>EDIT: even when i didn't call <code>connection.connect()</code>, it's still giving the same error <code>already connected</code>.</p>