18

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

arpitpanwar
  • 189
  • 1
  • 1
  • 8
  • 1
    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 code](https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html) – Krease Apr 27 '15 at 22:08
  • @Chris exactly, I've been digging around URLConnection source code to see what is going on, and the error shouldn't happen at all. – Mr.Me Apr 27 '15 at 22:14
  • 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 http://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()` – Krease Apr 27 '15 at 23:07
  • I am sending request to a web application hosted on tomcat on the same machine. Could that be causing an issue? – arpitpanwar Apr 27 '15 at 23:41
  • 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. – Krease Apr 28 '15 at 16:30
  • 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. – Rohitesh Nov 16 '15 at 06:26
  • @Rohitesh I was able to get around this problem by synchronizing access to this method. – arpitpanwar Nov 22 '15 at 22:31
  • @arpitpanwar: Synchronizing is also NOT solving the problem for me! :( – Rohitesh Nov 25 '15 at 09:08
  • Possible duplicate of [HttpURLConnection: java.lang.IllegalStateException: Already connected](http://stackoverflow.com/questions/23738940/httpurlconnection-java-lang-illegalstateexception-already-connected) – Sharcoux Jun 29 '16 at 07:58

4 Answers4

52

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.

Sharcoux
  • 5,546
  • 7
  • 45
  • 78
3

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"))
ItsPete
  • 2,363
  • 3
  • 27
  • 35
Rahul jha
  • 31
  • 5
0

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

sawa we
  • 521
  • 1
  • 4
  • 7
-3

put the stream.close(); in finally block

Alaa Abuzaghleh
  • 1,023
  • 6
  • 11