"Illegal State Exception: Already Connected" when using HttpURLConnection

Apart from the watches as mentioned in the previous comment, it might also occur if there is something wrong with the connection. For example:

I was setting a property:post.setRequestProperty("Ocp-Apim-Subscription-Key", "<>") after writing into OutPut Stream like post.getOutputStream().write(jsonBody.getBytes("UTF-8"));

It was like:

post.getOutputStream().write(jsonBody.getBytes("UTF-8"))
post.setRequestProperty("Ocp-Apim-Subscription-Key", "<>")

In this case, I was also getting "Already Connected". To fix it I made it like:

post.setRequestProperty("Ocp-Apim-Subscription-Key", "<>")
post.getOutputStream().write(jsonBody.getBytes("UTF-8"))

I got the same problem and solved it. In my case, it was caused because I had a forgotten watch for connection.getResponseCode() in my debugging interface in NetBeans. Hope it might help others making the same mistake.

If you have any watch relative to the response value of the request, such as getResponseCode(), getResponseMessage(), getInputStream() or even just connect(), you will get this error in debugging mode.

All of the previous methods implicitly call connect() and fire the request. So when you reach setDoOutput, the connection is already made.