title: HttpURLConnection: java.lang.IllegalStateException: Already connected
body: <p>I'm trying to use HttpURLClient to send some POST data to a server using the <code>HttpRestClient</code> class shown below. When executing</p>
  
  <pre><code>conn.setDoInput(true);
  </code></pre>
  
  <p>I get</p>
  
  <pre><code>java.lang.IllegalStateException: Already connected
  </code></pre>
  
  <p>I uninstalled the app, and still get the same error.</p>
  
  <p>In all the example I've seen openConnection is called before <code>setDoInput</code>. If, as its name suggests, <code>openConnection</code> opens a connection, it should never be used before `setDoInput, right? What am I missing?</p>
  
  <p>Maybe at some point it crashed before executing <code>disconnect</code>. Could that be the reason? If so, how can I disconnect the old connection?</p>
  
  <pre><code>public class HttpRestClient {
  static public int post(String urlStr, List&lt;NameValuePair&gt; data){
  
      HttpURLConnection conn = null;
  
      try {
  
          URL url = new URL(urlStr);
  
  
          conn = (HttpURLConnection) url.openConnection();
  
          conn.setDoInput(true);
          conn.setDoOutput(true);
  
          conn.setRequestMethod("POST");
  
          OutputStream os = conn.getOutputStream();
          BufferedWriter writer = new BufferedWriter(
                  new OutputStreamWriter(os, "UTF-8"));
          writer.write(getQuery(data));
          writer.flush();
          writer.close();
          os.close();
  
          InputStream is = conn.getInputStream();
  
          String dude = readIt(is);
  
          return 1;
  
      } catch (MalformedURLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          return 0;
      } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          return 0;
      }
      finally {
          if(conn!=null) conn.disconnect();
      }
  }
  }
  </code></pre>