简体   繁体   中英

How to check if URLConnection is already in connected state?

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().

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM