"Illegal State Exception: Already Connected" when using HttpURLConnection
Asked Answered
A

4

20

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

public boolean sendLinksToMaster(String ipport, List<String> links){

        boolean sent = false;
        String[] tokens = ipport.split(":");    
        String data = edu.cis555.searchengine.utils.Utils.generateLinks(links);
        HttpURLConnection conn=null;
        try{
            String encodedData = URLEncoder.encode(data, "UTF-8");
        try{

                String ip =tokens[0];
                String port = tokens[1];
                String path = edu.cis555.searchengine.utils.Constants.URL_ADD_LINK;
                System.setProperty("http.keepAlive", "false");
                URL u = new URL("http", ip, Integer.parseInt(port),"/"+path);

                conn = (HttpURLConnection)u.openConnection();
                //ERROR IN THIS LINE
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                OutputStream stream = conn.getOutputStream();
                stream.write(encodedData.getBytes());
                stream.close();

                if(conn.getResponseCode() == HttpURLConnection.HTTP_OK)
                    sent=true;

            //  LOG.debug(conn.getResponseCode());
                conn.disconnect();
            }catch(MalformedURLException mfe){
                LOG.debug(mfe.getMessage());
                if(conn!=null){
                    conn.disconnect();
                }
            }catch(IOException ioe){
                LOG.debug(ioe.getMessage());
                if(conn!=null){
                    conn.disconnect();
                }
            }

        }catch(Exception e){
            LOG.debug(e.getMessage());
            if(conn!=null){
                conn.disconnect();
            }
        }
        return sent;

    }

The stack trace displayed for the same is:

java.lang.IllegalStateException: Already connected
at java.net.URLConnection.setDoOutput(Unknown Source)
at edu.upenn.cis455.xpathengine.utils.pool.ThreadPool.sendLinksToMaster(ThreadPool.java:357)
at edu.upenn.cis455.xpathengine.utils.pool.ThreadPool$Worker.processAndAddToQueue(ThreadPool.java:314)
at edu.upenn.cis455.xpathengine.utils.pool.ThreadPool$Worker.run(ThreadPool.java:269)
at java.lang.Thread.run(Unknown Source)

I don't see anything I am doing wrong with sending the request. Could anyone point out what is missing or what am I doing wrong

Archdeaconry answered 27/4, 2015 at 21:47 Comment(9)
Based on the source for HTTPUrlConnection, it looks like it expects those methods (setDoOutput and setRequestMethod) to be called before the connection is open, which shouldn't be happening until you call conn.connect() Your code also looks similar in structure to the URLConnection sample codeRoodepoortmaraisburg
@Chris exactly, I've been digging around URLConnection source code to see what is going on, and the error shouldn't happen at all.Diagonal
Hmm... Trying this myself I'm not able to reproduce your issue - I just simplified it enough to throw it into a standalone main method, hardcoded the URL to docs.oracle.com, called url.openConnection() and stepped through conn.setDoOutput / conn.setRequestMethod without errors (verifying that connected==false at each step) - it wasn't opened until I called conn.getOutputStream()Roodepoortmaraisburg
I am sending request to a web application hosted on tomcat on the same machine. Could that be causing an issue?Archdeaconry
You should only be getting that issue if your code is reusing an open HttpURLConnection instead of creating a new one every time (as per your above code). Are you able to reproduce your issue if you simplify it into a standalone main method as I did? If not, then there is clearly some difference between what you're running here and that standalone class, and that should help you debug it.Roodepoortmaraisburg
arpitpanwar: Could you resolve this? This is happening to me too. @Chris: the problem could be because of connection pooling. Its picking up a reusable connection. Which is why you are not seeing it in the standalone mode.Cockalorum
@Cockalorum I was able to get around this problem by synchronizing access to this method.Archdeaconry
@arpitpanwar: Synchronizing is also NOT solving the problem for me! :(Cockalorum
Possible duplicate of HttpURLConnection: java.lang.IllegalStateException: Already connectedOdom
O
54

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.

Odom answered 28/6, 2016 at 9:29 Comment(5)
Wow! I was having the same issue, and sure enough i had an expression in my debug window for conn.getResponseCode() ... I removed this and it started worked. not sure why you got a downvote, but i just upvoted itSap
Thanks. I was sure this would help others as it is not obvious to debug ;)Odom
You're amazing sir. I had exactly the same expression inside my watches in Eclipse. Thanks for sharing.Arcturus
Incredible how many developers fall into the very same trap :-)Immune
This is the issue with implicit behaviours ;)Odom
Q
4

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"))
Quickfreeze answered 25/9, 2019 at 5:33 Comment(0)
N
0

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

Nagari answered 25/1, 2019 at 20:11 Comment(0)
C
-3

put the stream.close(); in finally block

Cowlick answered 27/4, 2015 at 22:31 Comment(2)
The code execution never reaches stream.close(). The exception is raised as soon as I call setDoOutputArchdeaconry
try kill the java process and then test your code againCowlick

© 2022 - 2024 — McMap. All rights reserved.