[英]“Illegal State Exception: Already Connected” when using HttpURLConnection
當我將DoOutput設置為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;
}
顯示的堆棧跟蹤是:
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)
發送請求時,我沒有看到任何錯誤。 任何人都可以指出缺少什么或我做錯了什么
我遇到了同樣的問題並解決了它。 就我而言,這是因為我在NetBeans的調試界面中忘記了對connection.getResponseCode()
監視。 希望它可以幫助其他人犯同樣的錯誤。
如果您有相對於請求響應值的任何監視,例如getResponseCode()
, getResponseMessage()
, getInputStream()
甚至只是connect()
,您將在調試模式下收到此錯誤。
所有以前的方法都隱式調用connect()
並觸發請求。 因此,當您達到setDoOutput
,已建立連接。
有時它就像確保你沒有http而不是https一樣容易。
把stream.close(); 在最后一塊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.