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
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 URLConnectionblocked 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?
