Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Illegal State Exception: Already Connected" when using HttpURLConnection

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

like image 860
arpitpanwar Avatar asked Apr 27 '15 21:04

arpitpanwar


2 Answers

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.

like image 64
Sharcoux Avatar answered Nov 13 '22 19:11

Sharcoux


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"))
like image 35
Rahul jha Avatar answered Nov 13 '22 19:11

Rahul jha