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
setDoOutput
andsetRequestMethod
) to be called before the connection is open, which shouldn't be happening until you callconn.connect()
Your code also looks similar in structure to the URLConnection sample code – Roodepoortmaraisburgurl.openConnection()
and stepped throughconn.setDoOutput / conn.setRequestMethod
without errors (verifying thatconnected==false
at each step) - it wasn't opened until I calledconn.getOutputStream()
– RoodepoortmaraisburgHttpURLConnection
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