Reputation: 2019
I want to check the connected state of a URLConnection in Java.
I want to write a toString(URLConnection)
method to print all the header-data (Request & Response) of the connection.
But the toString()
method should only print the Response-data when the connection is already established!
The problem here is that the connection is established once any getter or method is called that accesses the response data.
Thus i can not simply call getHeaderFields() since this would actually trigger the connect. This helper method should not influence the internal state of the URLConnection. It should only passively read the data from it (that is already there and skip the parts that are not loaded yet.
So in short i need a way to check if the URLConnection is in connected state already before accessing any method that triggers connect().
Upvotes: 2
Views: 3251
Reputation: 38724
Make a subclass of URLConnection
, in this you can access the connected
field which has protected
access modifier.
Other than that you could either call one of the methods that throw an exception if the connection is already established like uc.setDefaultUseCaches(uc.getDefaultUseCaches())
and catch the exception, or use reflection to get the value of the connected
field.
Upvotes: 0
Reputation: 2019
Due to the nature of the setDoOutput(boolean)
(Java-Doc) method it can be used to detect the internal state like this:
public static boolean isConnected(URLConnection con) {
try {
con.setDoOutput(con.getDoOutput()); // throws IllegalStateException if connected
return false;
} catch (IllegalStateException e) {
return true;
}
}
Here the current implementation of the method for reference:
public void setDoOutput(boolean dooutput) {
if (connected)
throw new IllegalStateException("Already connected");
doOutput = dooutput;
}
Upvotes: 2