使用 HttpURL 连接时的“非法状态异常:已连接”
2022-09-03 03:53:10
当我将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)
我没有看到我在发送请求时做错了什么。任何人都可以指出缺少什么或我做错了什么