java.net.ConnectionException while trying to connect to local host

Viewed 252

I set up a PHP server on localhost:80. However, when I tried to connect it with HttpUrlConnection, it threw an exception.

package test;

public class Main {
    public static void main(String[] args) throws IOException {
        /* Error thrown on the following line */
        new URL("http://localhost/").openConnection().connect(); 
    }
}

Stack trace:

Exception in thread "main" java.net.ConnectException: Connection refused: connect
    at java.base/java.net.PlainSocketImpl.connect0(Native Method)
    at java.base/java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:101)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
    at java.base/java.net.Socket.connect(Socket.java:609)
    at java.base/java.net.Socket.connect(Socket.java:558)
    at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:182)
    at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474)
    at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569)
    at java.base/sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
    at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:341)
    at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:362)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1253)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1187)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1081)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1015)
    at test.Main.main(Main.java:6)

The index.php is simply <?php echo "Ello World"; ?>

I've tried to access the page with Chrome and cURL, but that works perfectly

Accessing the page by typing "http://localhost/"

C:\Users\User>curl -XGET "http://localhost/"
Ello World

Then, I tried to send a GET request to google:

new URL("http://google.com/").openConnection().connect();

All good, no errors

I later searched for the related errors with the keywords "ConnectException", "connection refused", "java localhost" ..., still, no luck.

  • The PHP server and Java is running on the same machine. No emulator. Just PHP and IntelliJ IDEA
  • The PHP server doesn't receive any incoming request, because there is no log output
  • I am using the HTTP protocol because the PHP server doesn't have SSL enabled
  • Changing the URL to "http://localhost:80/", "http://127.0.0.1/" or "http://127.0.0.1:80/" doesn't help

My suspicion:

  • PHP server doesn't accept requests with URLConnection, because they are incompatible
  • URLConnection blocked HTTP request because it is "insecure"
  • The firewall things is blocking the request, but as far as I known, firewall doesn't block connections within the same machine, Right?

Any Ideas?

1 Answers

According to the use case you described, the most probably reason would be that the firewall or some antivirus software is blocking your Java program, there is nothing that prevents the firewall to block connections within the same machine.

Please, and excuse me to say, but be sure as well that the server is actually running when the test is executed, perhaps it is terminated or stopped for any reason: I am saying this because it is strange that your test works successfully against google.com and not for localhost.

The PHP server will accept requests with URLConnection, at first glance there is nothing in the Java HttpURLConnection implementation that could cause such behavior, and URLConnection can connect to secure or insecure sites: take for instance the Google example you exemplified.

Finally, although I think there shouldn't be nothing wrong with using the connect method, try something different in your code, the web is plenty of examples of how to read some URL with HttpURLConnection. Take for instance this example, adapted from the Android documentation - please, excuse the simplicity of the code:

URL url = new URL("http://localhost/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
  InputStream in = new BufferedInputStream(urlConnection.getInputStream());
  
  String line;
  StringBuffer response = new StringBuffer();

  while ((line = in.readLine()) != null) {
    response.append(line);
  }

  in.close();

  System.out.println("Response:\n" + response.toString());
} finally {
  urlConnection.disconnect();
}

According to your comments, and the output from curl you provided:

> GET / HTTP/1.1
> Host: localhost
> User-Agent: curl/7.83.1
> Accept: */*

try including the same headers curl is already providing: as I mentioned in my comments, I have never experienced this behavior, but it could be of help. Please, try the following, for example:

URL url = new URL("http://localhost/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
  // Note the headers provided: try to test it and see if it works
  urlConnection.setRequestProperty("Host", "localhost");
  urlConnection.setRequestProperty("User-Agent", "curl/7.83.1");
  urlConnection.setRequestProperty("Accept", "*/*");

  InputStream in = new BufferedInputStream(urlConnection.getInputStream());
  
  String line;
  StringBuffer response = new StringBuffer();

  while ((line = in.readLine()) != null) {
    response.append(line);
  }

  in.close();

  System.out.println("Response:\n" + response.toString());
} finally {
  urlConnection.disconnect();
}
Related