“Illegal State Exception: Already Connected” when using HttpURLConnection

后端 未结 4 1693
鱼传尺愫
鱼传尺愫 2020-12-06 17:06

I get an illegal state exception when i set DoOutput to true.

public boolean sendLinksToMaster(String ipport, List links){

        boolean sen         


        
相关标签:
4条回答
  • 2020-12-06 17:21

    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.

    0 讨论(0)
  • 2020-12-06 17:34

    sometimes it is as easy as make sure you do not have http in stead of https.

    0 讨论(0)
  • 2020-12-06 17:38

    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"))
    
    0 讨论(0)
  • 2020-12-06 17:38

    put the stream.close(); in finally block

    0 讨论(0)
提交回复
热议问题