Java HttpUrlConnection throws Connection Refused

Gabriel Matusevich picture Gabriel Matusevich · Sep 20, 2014 · Viewed 10.2k times · Source

I know there are several question regarding this topic But I did't find an answer in any of them.

I'm trying to open a connection to my local server but I keep getting connection refused.

I have the server running and I tested the connection with the Browser and with a Google App called Postman and it works.

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.

testing in Postman the URL returns a User as it should...

If I replace the url with "http://www.google.com" It Works fine.

here is my 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());


    }
}

Answer

David Cain picture David Cain · Mar 22, 2016

I have similar code that is working, but my request header is a lot simpler. Basically just:

con.setRequestProperty("User-Agent", "Mozilla/5.0");

If simplifying the header does not help, I would capture the traffic when using your browser with something like fiddler and then making the request look exactly like that.