问题描述
当我将DoOutput设置为true时,我收到非法状态异常。
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;
}
显示的堆栈跟踪是:
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
推荐答案
我遇到了同样的问题并解决了它。就我而言,这是因为我在NetBeans的调试界面中忘记了 connection.getResponseCode()
。希望它可以帮助其他人犯同样的错误。
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.
如果你有相对于请求响应值的任何监视,例如 getResponseCode()
, getResponseMessage()
, getInputStream()
甚至只是 connect()
,你会在调试模式下得到这个错误。
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.
所有以前的方法都隐式调用 connect( )
并触发请求。因此,当您到达 setDoOutput
时,已建立连接。
All of the previous methods implicitly call connect()
and fire the request. So when you reach setDoOutput
, the connection is already made.
这篇关于“非法国家例外:已经连接”使用HttpURLConnection时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!