Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: HttpURLConnection Issues with IllegalStateArgument: Already Connected

This question seems clear what is happening: I already have a connection open, the problem is I don't know why.

Right now I'm just testing my http login and out.

Login:

HttpURLConnection con = openConnection(URLGenerator.getLoginURL(), true, true,"POST");
        String content = ...;
        writeToOutput(con, content);
        con.connect();
        String cookieVal = con.getHeaderField("Set-Cookie");
        if(cookieVal != null)
        {
            sessionId = cookieVal.substring(0, cookieVal.indexOf(";"));
        }
        con.disconnect();
        return con.getResponseCode();

Logout:

    HttpURLConnection con = openConnection(URLGenerator.getLogoutURL(), true, true,"GET");
    String content = ...;
    writeToOutput(con, content);
    setCookies(con);
    con.connect();
    con.disconnect();
    return con.getResponseCode();

and for the code lovers the function OpenConnection (because I know the first thing people are going to ask is "where is this function"

public static final HttpURLConnection openConnection(URL url, boolean in, boolean out,String requestMethode) throws IOException{
        HttpURLConnection con = (HttpURLConnection) url.openConnection ();
        con.setDoInput(in);
        con.setDoOutput (out);
        if(requestMethode == null){
            requestMethode = "GET";
        }
        con.setRequestMethod(requestMethode);
        con.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");
        return con;
    }

This is the function that triggers the java.lang.IllegalStateException: Already connected

public static final void setCookies(HttpURLConnection con){
        if(sessionId != null)
        {
            con.setRequestProperty("Cookie", sessionId);
        }
    }

What I don't get is why the connection is still open.

I even tried to call disconnect but it doesn't work.

I thought the principal was to set up a HttpURLConncetion object and do connect to execute the request, receive the result and that terminated the connection.

Any ideas?

Thanks Jason

like image 447
Jason Rogers Avatar asked Mar 20 '11 12:03

Jason Rogers


1 Answers

You need to set cookies (request header values) before you write to the request body. You can't change the request headers anymore when the first bit of the request body is been sent.

So, change

writeToOutput(con, content);
setCookies(con);

to

setCookies(con);
writeToOutput(con, content);

and this problem should disappear.

like image 103
BalusC Avatar answered Nov 24 '22 08:11

BalusC