HttpURLConnection Already connected

moondaisy picture moondaisy · Aug 2, 2016 · Viewed 9.3k times · Source

I'm trying to replicate this, the copy sentence from openstack swift v1 (which works just fine):

curl -i $publicURL/GXPrueba/StorageAPI/PruebaStorageCopy.png -X PUT -H "X-Auth-Token:  $token" -H "X-Copy-From: /GXPrueba/StorageAPI/PruebaStorage.png" -H "Content-Length: 0"

Like this:

private void copy(String originContainer, String origin, String destinationContainer, String destination) {
    try {
        URL url = new URL(storageUrl + DELIMITER + destinationContainer + DELIMITER + destination);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("X-Auth-Token", authToken);
        conn.setRequestProperty("X-Copy-From", DELIMITER + originContainer + DELIMITER + origin);
        conn.setRequestProperty("Content-Length", "0");

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            System.err.println("Error while copying the object: " + conn.getResponseCode());
        }
        conn.disconnect();

    } catch (MalformedURLException e) {
        System.err.println("Error while copying the object: " + e.getMessage());
    } catch (IOException e) {
        System.err.println("Error while copying the object: " + e.getMessage());
    }
}

And I keep getting java.lang.IllegalStateException: Already connected exception at different lines everytime. I already tried the other solutions I found (like removing the setDoInput) but nothing seems to work.

Here is the stack trace

Exception in thread "main" java.lang.IllegalStateException: Already connected
    at java.net.URLConnection.setDoOutput(URLConnection.java:900)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.setDoOutput(HttpsURLConnectionImpl.java:455)
    at javaapplication3.ExternalProviderBluemix.copy(ExternalProviderBluemix.java:212)
    at javaapplication3.ExternalProviderBluemix.copy(ExternalProviderBluemix.java:202)
    at javaapplication3.JavaApplication3.main(JavaApplication3.java:39)
C:\Users\lsarni\AppData\Local\NetBeans\Cache\8.1\executor-snippets\debug.xml:83: Java returned: 1
BUILD FAILED (total time: 24 seconds)

Answer

moondaisy picture moondaisy · Aug 4, 2016

I found out the solution to this problem was what @Sharcoux posted here, which explained why sometimes it would work just fine.

So to solve this while debugging on NetBeans you need to remove from the watch all the expressions that use conn (such conn.setDoOutPut(), etc.).