title: Java HttpUrlConnection throws Connection Refused
body: <p>I know there are several question regarding this topic But I did't find an answer in any of them.</p>
  
  <p>I'm trying to open a connection to my local server but I keep getting connection refused.</p>
  
  <p>I have the server running and I tested the connection with the Browser and with a Google App called Postman and it works.</p>
  
  <p>It's failing when opening the connection as if there where nothing to connect to. or maybe something is blocking the connection? I tested with firewall and antivirus down, no luck.</p>
  
  <p>testing in Postman the URL returns a User as it should...</p>
  
  <p>If I replace the url with "<a href="http://www.google.com">http://www.google.com</a>" It Works fine.</p>
  
  <p>here is my code:</p>
  
  <pre><code>import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.net.HttpURLConnection;
  import java.net.MalformedURLException;
  import java.net.URL;
  
  /**
   *
   * @author Gabriel
   */
  public class HttpConnection {
  
      public HttpConnection() {
  
      }
  
      public void makeRequest() throws MalformedURLException, IOException {
  
          String url = "http://localhost:8000/users/1";
  
      URL obj = new URL(url);
      HttpURLConnection con = (HttpURLConnection) obj.openConnection();
      // optional default is GET
      con.setRequestMethod("GET");
  
      //add request header
      con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36");
          con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
          con.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
          con.setRequestProperty("Accept-Language", "en-US,en;q=0.8,es;q=0.6");
          con.setRequestProperty("Connection", "keep-alive");
          con.setRequestProperty("Host", "localhost:8000");
  
      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'GET' request to URL : " + url);
      System.out.println("Response Code : " + responseCode);
  
      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuffer response = new StringBuffer();
  
      while ((inputLine = in.readLine()) != null) {
              response.append(inputLine);
      }
      in.close();
  
      //print result
      System.out.println(response.toString());
  
  
      }
  }
  </code></pre>