[java] Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

I'm getting a ConnectException: Connection timed out with some frequency from my code. The URL I am trying to hit is up. The same code works for some users, but not others. It seems like once one user starts to get this exception they continue to get the exception.

Here is the stack trace:

java.net.ConnectException: Connection timed out
Caused by: java.net.ConnectException: Connection timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.Socket.connect(Socket.java:516)
    at java.net.Socket.connect(Socket.java:466)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:365)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:477)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:214)
    at sun.net.www.http.HttpClient.New(HttpClient.java:287)
    at sun.net.www.http.HttpClient.New(HttpClient.java:299)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:796)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:748)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:673)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:840)

Here is a snippet from my code:

URLConnection urlConnection = null;
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;

try {
    URL url = new URL(urlBase);
    urlConnection = url.openConnection();

    outputStream = urlConnection.getOutputStream(); // exception occurs on this line
    outputStreamWriter = new OutputStreamWriter(outputStream);
    inputStream = urlConnection.getInputStream();
    String response = IOUtils.toString(inputStream);
    return processResponse(urlString, urlBase, response);
} catch (IOException e) {
    throw new Exception("Error querying url: " + urlString, e);
} finally {

This question is related to java connection urlconnection connectexception

The answer is

Connection timeouts (assuming a local network and several client machines) typically result from

a) some kind of firewall on the way that simply eats the packets without telling the sender things like "No Route to host"

b) packet loss due to wrong network configuration or line overload

c) too many requests overloading the server

d) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c).

Hope this helps.

If the URL works fine in the web browser on the same machine, it might be that the Java code isn't using the HTTP proxy the browser is using for connecting to the URL.

The error message says it all: your connection timed out. This means your request did not get a response within some (default) timeframe. The reasons that no response was received is likely to be one of:

a) The IP/domain or port is incorrect

b) The IP/domain or port (i.e service) is down

c) The IP/domain is taking longer than your default timeout to respond

d) You have a firewall that is blocking requests or responses on whatever port you are using

e) You have a firewall that is blocking requests to that particular host

f) Your internet access is down

g) Your live-server is down i.e in case of "rest-API call".

Note that firewalls and port or IP blocking may be in place by your ISP

I'd recommend raising the connection timeout time before getting the output stream, like so:


Where 1000 is in milliseconds (1000 milliseconds = 1 second).

  • try to do the Telnet to see any firewall issue
  • perform tracert/traceroute to find number of hops

I solved my problem with:

System.setProperty("https.proxyHost", "myProxy");
System.setProperty("https.proxyPort", "80");

or http.proxyHost...

This can be a IPv6 problem (the host publishes an IPv6 AAAA-Address and the users host thinks it is configured for IPv6 but it is actually not correctly connected). This can also be a network MTU problem, a firewall block, or the target host might publish different IP addresses (randomly or based on originators country) which are not all reachable. Or similliar network problems.

You cant do much besides setting a timeout and adding good error messages (especially printing out the hosts' resolved address). If you want to make it more robust add retry, parallel trying of all addresses and also look into name resolution caching (positive and negative) on the Java platform.

Why would a “java.net.ConnectException: Connection timed out” exception occur when URL is up?

Because the URLConnection (HttpURLConnection/HttpsURLConnection) is erratic. You can read about this here and here. Our solution were two things:

a) set the ContentLength via setFixedLengthStreamingMode

b) catch any TimeoutException and retry if it failed.

There is a possibility that your IP/host are blocked by the remote host, especially if it thinks you are hitting it too hard.

The reason why this happened to me was that a remote server was allowing only certain IP addressed but not its own, and I was trying to render the images from the server's URLs... so everything would simply halt, displaying the timeout error that you had...

Make sure that either the server is allowing its own IP, or that you are rendering things from some remote URL that actually exists.

Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with connection tag:

Apache Server (xampp) doesn't run on Windows 10 (Port 80) "Proxy server connection failed" in google chrome Failed to connect to mysql at with user root access denied for user 'root'@'localhost'(using password:YES) "The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate Login to Microsoft SQL Server Error: 18456 How do I start Mongo DB from Windows? java.rmi.ConnectException: Connection refused to host:; mySQL Error 1040: Too Many Connection org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android What is the functionality of setSoTimeout and how it works? java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) How to create user for a db in postgresql? Eclipse : Failed to connect to remote VM. Connection refused. MySQL show status - active or total connections? CodeIgniter: Unable to connect to your database server using the provided settings Error Message Draw a connecting line between two elements How to grant remote access permissions to mysql server for user? Setting up connection string in ASP.NET to SQL SERVER How to kill MySQL connections HttpClient 4.0.1 - how to release connection? How do I connect to mongodb with node.js (and authenticate)? Python [Errno 98] Address already in use How do multiple clients connect simultaneously to one port, say 80, on a server? What port is used by Java RMI connection? What is the difference between connection and read timeout for sockets? Using R to download zipped data file, extract, and import data How to check if a socket is connected/disconnected in C#? Connection string with relative path to the database file Rmi connection refused with localhost MySQL connection not working: 2002 No such file or directory Cannot connect to MySQL 4.1+ using old authentication How to create a bash script to check the SSH connection? How to check if internet connection is present in Java? How to test an Internet connection with bash? How to detect the physical connected state of a network cable/connector? Instantly detect client disconnection from server socket How to determine total number of open/active connections in ms sql server 2005 Artificially create a connection timeout error Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up? java.net.SocketException: Connection reset Oracle - What TNS Names file am I using?

Questions with urlconnection tag:

Can you explain the HttpURLConnection connection process? Unable to resolve host "<insert URL here>" No address associated with hostname java.io.IOException: Server returned HTTP response code: 500 Convenient way to parse incoming multipart/form-data parameters in a Servlet Java URLConnection Timeout How to use java.net.URLConnection to fire and handle HTTP requests? Upload files from Java client to a HTTP server Java: how to use UrlConnection to post request with authorization? Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

Questions with connectexception tag:

Hadoop cluster setup - java.net.ConnectException: Connection refused Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?