Java:HttpURLConnection问题,IllegalStateArgument:已连接

Java:HttpURLConnection问题,IllegalStateArgument:已连接,java,httpurlconnection,illegalstateexception,Java,Httpurlconnection,Illegalstateexception,这个问题似乎很清楚发生了什么:我已经打开了一个连接,问题是我不知道为什么 现在我正在测试我的http登录和退出 登录: HttpURLConnection con = openConnection(URLGenerator.getLoginURL(), true, true,"POST"); String content = ...; writeToOutput(con, content); con.connect(); Strin

这个问题似乎很清楚发生了什么:我已经打开了一个连接,问题是我不知道为什么

现在我正在测试我的http登录和退出

登录:

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();
注销:

    HttpURLConnection con = openConnection(URLGenerator.getLogoutURL(), true, true,"GET");
    String content = ...;
    writeToOutput(con, content);
    setCookies(con);
    con.connect();
    con.disconnect();
    return con.getResponseCode();
对于代码爱好者来说,函数OpenConnection(因为我知道人们首先要问的是“这个函数在哪里?”

这是触发java.lang.IllegalStateException的函数:已连接

public static final void setCookies(HttpURLConnection con){
        if(sessionId != null)
        {
            con.setRequestProperty("Cookie", sessionId);
        }
    }
我不明白的是为什么连接仍然打开

我甚至试着给disconnect打电话,但没用

我认为主要是设置一个httpurlconception对象并进行连接以执行请求、接收结果并终止连接

有什么想法吗

感谢Jason

在写入请求正文之前,您需要设置Cookie(请求标头值)。当发送请求正文的第一位时,您不能再更改请求标头

所以,改变

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


这个问题应该会消失。

好的,谢谢,我认为这与顺序无关(我将它视为一个对象,您可以在其中设置值并发送:$我对urlconnection的理解有误:D)不客气。
connect()
调用是不必要的。一些
URLConnection
方法已经隐式地这样做了。
disconnect()
也不是绝对必要的。它将在幕后基本上立即终止缓存的连接(当它过期时无论如何都会被终止)。
writeToOutput(con, content);
setCookies(con);
setCookies(con);
writeToOutput(con, content);